/*
 * Copyright (c) 2013 哈尔滨亿时代数码科技开发有限公司（www.hrbesd.com）. All rights reserved.
 * 
 * HRBESD PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.esd.ps;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.ibatis.binding.BindingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.esd.db.model.AlipayInfo;
import com.esd.db.model.InspectorMarkTimeRecord;
import com.esd.db.model.InspectorRecordWithBLOBs;
import com.esd.db.model.VtdNotice;
import com.esd.db.model.VtdParameter;
import com.esd.db.model.inspector;
import com.esd.db.model.inspectorrecord;
import com.esd.db.model.markTimeMethod;
import com.esd.db.model.packWithBLOBs;
import com.esd.db.model.taskWithBLOBs;
import com.esd.db.model.worker;
import com.esd.db.model.workerRecord;
import com.esd.db.service.InspectorMarkTimeRecordService;
import com.esd.db.service.InspectorRecordService;
import com.esd.db.service.InspectorService;
import com.esd.db.service.MarkTimeMethodService;
import com.esd.db.service.PackService;
import com.esd.db.service.SalaryService;
import com.esd.db.service.TaskService;
import com.esd.db.service.VtdNoticeService;
import com.esd.db.service.VtdParameterService;
import com.esd.db.service.WorkerRecordService;
import com.esd.db.service.WorkerService;
import com.esd.ps.model.WorkerRecordTrans;
import com.esd.ps.util.TaskMarkTime;
import com.esd.ps.util.TaskMarkTime1;

/**
 * 审核员
 * 
 * @author chen
 * 
 */
@Controller
@RequestMapping("/security")
public class InspectorController {
	private static final Logger logger = LoggerFactory.getLogger(InspectorController.class);

	@Autowired
	private WorkerRecordService workerRecordService;
	@Autowired
	private TaskService taskService;
	@Autowired
	private PackService packService;
	@Autowired
	private WorkerService workerService;
	@Autowired
	private InspectorRecordService inspectorRecordService;
	@Autowired
	private InspectorService inspectorService;
	@Autowired
	private SalaryService salaryService;
	@Autowired
	private VtdParameterService paramService;
	@Autowired
	private VtdNoticeService noticeService;
	@Autowired
	InspectorMarkTimeRecordService imtrService;
	/**
	 * 审核管理员
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/inspectorManager", method = RequestMethod.GET)
	public ModelAndView inspectorManagerGet(HttpSession session) {
		List<VtdParameter> list = paramService.selectParamByType(Constants.WORK_GROUP);
//		return new ModelAndView("inspector/inspectorM");
		
		ModelAndView mv = new ModelAndView();
		mv.setViewName("inspector/inspectorM");
		mv.addObject("workGroupList", list);
		return mv;
	}
	/**
	 * 审核管理员
	 * @param userName
	 * @param timeMark
	 * @param page
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/inspectorManager", method = RequestMethod.POST)
	@ResponseBody
	public  Map<String, Object> inspectorManagerPost(String userName, int timeMark, int page, HttpSession session) {
		logger.debug("userName:{},timeMark:{}", userName, timeMark);
		Map<String, Object> map = new HashMap<String, Object>();
		int userId = Integer.parseInt(session.getAttribute(Constants.USER_ID).toString());
		int inspectorId = 0;
		try{
			inspectorId = inspectorService.getInspectorIdByUserId(userId);
		}catch(BindingException n){
			inspectorId = -1;
		}	
		//int insCount = inspectorService.getCount();
		int totle = workerRecordService.getWorkerIdCountGroupByWorkerId(inspectorId,userName, timeMark, 1, 3,Constants.LIMIT_MIN,null);
		int count = 0;
		count = totle;
//		if(totle == 0){
//			return null;
//		}
//		count = totle/insCount;
//		if(count == 0){
//			count = 1;
//		}
		List<Map<String, Object>> list = workerRecordService.getWorkerIdGroupByWorkerId(inspectorId,userName, timeMark, 1, 3, page, Constants.ROW,Constants.LIMIT_MIN,null);
		//SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATETIME_FORMAT);
		List<Map<String, Object>> list1 = new ArrayList<>();
		long nowTimeMsec = new Date().getTime();  //现在时间的毫秒数
		long twoDaysMsec = 172800000; //两天时间的毫秒数  172800000  2*24*60*60*1000
		for (Iterator<Map<String, Object>> iterator = list.iterator(); iterator.hasNext();) {
			Map<String, Object> map1 = (Map<String, Object>) iterator.next();
			logger.debug("map1:{}",map1);
			int workerId = Integer.parseInt(map1.get("worker_id").toString());
			String workerRealName = workerService.getWorkerRealNameByWorkerId(workerId);
			map1.put("workerRealName", workerRealName);
			//计算审核超时剩余时间  超时时间为48小时  
			Date tempDate = (Date)map1.get("task_upload_time");
			long uploadTimeMsec = tempDate.getTime();
			if(uploadTimeMsec + twoDaysMsec > nowTimeMsec){//未超时
				map1.put("inspTimeoutFlag", false);
				long endMsec = uploadTimeMsec + twoDaysMsec;
				map1.put("endMsec", endMsec);
			}else if(uploadTimeMsec + twoDaysMsec < nowTimeMsec){ //已超时
				map1.put("inspTimeoutFlag", true);
				map1.put("endMsec", 0);
			}else{ //正好相等 也是有可能的
				map1.put("inspTimeoutFlag", true);
				map1.put("endMsec", 0);
			}
			list1.add(map1);
		}		
		int totlePage = (int) Math.ceil((double) count / (double) Constants.ROW);
		List<inspector> insList= inspectorService.getAll();
		map.put("inspectorIds", insList);
		map.put(Constants.LIST, list1);
		map.put(Constants.TOTLE, count);
		map.put(Constants.TOTLE_PAGE, totlePage);
		return map;
	}

	/**
	 * 审核员列表页
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/inspector", method = RequestMethod.GET)
	public ModelAndView inspectorGet(HttpSession session) {
		ModelAndView mv = new ModelAndView();
		//查询是否有被巡审退回的数据
		int userId = Integer.parseInt(session.getAttribute("userId").toString());
		inspector ins = inspectorService.getinspectorByUserId(userId);
		int sendbackCount = workerRecordService.querySendbackListCountByInspectorId(ins.getInspectorId());
		//查询未完成包的批次  就是报名外的大包名
		List<String> list = packService.queryAllBatchInfo();
		if(sendbackCount>0){
			mv.addObject("hasSendback", true);
		}else{
			mv.addObject("hasSendback", false);
		}
		mv.addObject("batchNames",list);
		mv.setViewName("inspector/inspector");
		return mv;
	}

	/**
	 * 审核员列表页
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/inspector", method = RequestMethod.POST)
	@ResponseBody
	public  Map<String, Object> inspectorPost(String userName, String packBatchName, int timeMark, int page, HttpSession session) {
		logger.debug("userName:{},timeMark:{}", userName, timeMark);
		Map<String, Object> map = new HashMap<String, Object>();
		Object obj = this.getNotice(session);
		map.put("notice", obj);
		//需求变更  审核员查询通过工作组id 不需要指派    2016-06-24
//		int userId = Integer.parseInt(session.getAttribute(Constants.USER_ID).toString());
//		int inspectorId = 0;
//		try{
//			inspectorId = inspectorService.getInspectorIdByUserId(userId);
//		}catch(BindingException n){
//			inspectorId = -1;
//		}
		String workGroupCode = session.getAttribute(Constants.WORK_GROUP).toString(); //获取登录的审核员的工作组代码
		int inspectorId = -1;
//		int insCount = inspectorService.getCount();
		int totle = workerRecordService.getWorkerIdCountGroupByWorkerId(inspectorId,userName, timeMark, 1, 3,
				Constants.LIMIT_MIN,workGroupCode,packBatchName);
		int count = 0;
		count = totle;
//		if(totle == 0){
//			return null;
//		}
//		count = totle/insCount;
//		if(count == 0){
//			count = 1;
//		}
		List<Map<String, Object>> list = workerRecordService.getWorkerIdGroupByWorkerId(inspectorId,userName, timeMark, 1, 3,
				page, Constants.ROW,Constants.LIMIT_MIN,workGroupCode, packBatchName);
		//SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATETIME_FORMAT);
		List<Map<String, Object>> list1 = new ArrayList<>();
		long nowTimeMsec = new Date().getTime();  //现在时间的毫秒数
		long twoDaysMsec = 172800000; //两天时间的毫秒数  172800000  2*24*60*60*1000
		for (Iterator<Map<String, Object>> iterator = list.iterator(); iterator.hasNext();) {
			Map<String, Object> map1 = (Map<String, Object>) iterator.next();
			logger.debug("map1:{}",map1);
			int workerId = Integer.parseInt(map1.get("worker_id").toString());
			String workerRealName = workerService.getWorkerRealNameByWorkerId(workerId);
			map1.put("workerRealName", workerRealName);
			//计算审核超时剩余时间  超时时间为48小时  
			Date tempDate = (Date)map1.get("task_upload_time");
			long uploadTimeMsec = tempDate.getTime();
			if(uploadTimeMsec + twoDaysMsec > nowTimeMsec){//未超时
				map1.put("inspTimeoutFlag", false);
				long endMsec = uploadTimeMsec + twoDaysMsec;
				map1.put("endMsec", endMsec);
			}else if(uploadTimeMsec + twoDaysMsec < nowTimeMsec){ //已超时
				map1.put("inspTimeoutFlag", true);
				map1.put("endMsec", 0);
			}else{ //正好相等 也是有可能的
				map1.put("inspTimeoutFlag", true);
				map1.put("endMsec", 0);
			}
			list1.add(map1);
		}		
		//查询是否有被巡审退回的数据
		int userId = Integer.parseInt(session.getAttribute("userId").toString());
		inspector ins = inspectorService.getinspectorByUserId(userId);
		int sendbackCount = workerRecordService.querySendbackListCountByInspectorId(ins.getInspectorId());
		if(sendbackCount>0){
			map.put("hasSendback", true);
		}else{
			map.put("hasSendback", false);
		}
		
		int totlePage = (int) Math.ceil((double) count / (double) Constants.ROW);
		map.put(Constants.LIST, list1);
		map.put(Constants.TOTLE, count);
		map.put(Constants.TOTLE_PAGE, totlePage);
		return map;
	}
	/**
	 * 分配任务
	 * @param arr
	 * @param inspectorId
	 * @return
	 */
	@RequestMapping(value = "/assignT", method = RequestMethod.POST)
	@ResponseBody
	public  Map<String, Object> assignTPost(String workerIds,int inspectorId) {
		logger.debug("workerIds:{},inspectorId:{}", workerIds, inspectorId);
		Map<String, Object> map = new HashMap<String, Object>();
		String[] workerId = workerIds.split("/");
		int l = workerId.length;
		if(l < 1){
			map.clear();
			map.put(Constants.REPLAY, 0);
			return map;
		}
		for(int i=0;i < l;i++){
			int id = Integer.parseInt(workerId[i]);
			workerRecordService.updateByWorkerId(5, -1, id, "", inspectorId, null, -1);
		}
		map.clear();
		map.put(Constants.REPLAY, 1);
		return map;
	}
	/**
	 * 审核页
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/inspectorList", method = RequestMethod.GET)
	public ModelAndView inspectorListGet(int workerId, int percent, String uploadUUID, String showInvalidTask) {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("inspector/inspectorList");
		mv.addObject("workerId", workerId);
		mv.addObject("percent", percent);
		mv.addObject("uploadUUID", uploadUUID);
		mv.addObject("showInvalidTask", showInvalidTask);
		System.out.println(showInvalidTask);
		List<VtdParameter> errorTypeList = paramService.selectParamByType(Constants.ERROR_TYPE);
		mv.addObject("errorTypeList",errorTypeList);
		return mv;
	}

	/**
	 * 审核页
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/inspectorList", method = RequestMethod.POST)
	@ResponseBody
	public  Map<String, Object> inspectorListPost(int workerId,int percent, String uploadUUID, String showInvalidTask, HttpSession session) {
		Map<String, Object> map = new HashMap<>();
		String workGroupCode = session.getAttribute(Constants.WORK_GROUP).toString(); //获取登录的审核员的工作组代码
//		int userId = Integer.parseInt(session.getAttribute(Constants.USER_ID).toString());
//		int inspectorId = 0;
//		try{
//			inspectorId = inspectorService.getInspectorIdByUserId(userId);
//		}catch(BindingException n){
//			inspectorId = -1;
//		}
		
		System.out.println(showInvalidTask);
		
		
		if(uploadUUID.equals("undefined")){
			uploadUUID = null;
		}
		int inspectorId = -1;
		List<workerRecord> list = workerRecordService.getTaskByWorkerId(inspectorId, workerId, 3, 1,workGroupCode,uploadUUID);
		List<WorkerRecordTrans> list2 = new ArrayList<>();
		SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATETIME_FORMAT);
		double taskMarkTime = 0.00;
		for (Iterator<workerRecord> iterator = list.iterator(); iterator.hasNext();) {
			workerRecord workerRecord = (workerRecord) iterator.next();
			WorkerRecordTrans workerRecordTrans = new WorkerRecordTrans();	
			if(showInvalidTask.equals(Constants.DO_NOT_SHOW_INVALID_TASK)){
				if(workerRecord.getTaskMarkTime() == 0){
					continue;
				}
			}
			workerRecordTrans.setTaskName(workerRecord.getTaskName().substring(0, workerRecord.getTaskName().lastIndexOf("@")));
			workerRecordTrans.setTaskId(workerRecord.getTaskId());
			if(workerRecord.getTaskUploadTime() == null){
				workerRecordTrans.setTaskUploadTime(sdf.format(new Date()));
			}else{
				workerRecordTrans.setTaskUploadTime(sdf.format(workerRecord.getTaskUploadTime()));
			}	
			workerRecordTrans.setTaskMarkTime(workerRecord.getTaskMarkTime());
			taskMarkTime = taskMarkTime + workerRecord.getTaskMarkTime();
			list2.add(workerRecordTrans);
		}
		map.clear();
		if (list2 == null || list2.size() == 0) {
			map.put("firstDate", "");
			map.put("lastDate", "");
			map.put("list", "");
		} else {
			map.put("firstDate", list2.get(0).getTaskUploadTime());
			map.put("lastDate", list2.get(list2.size() - 1).getTaskUploadTime());
			//System.out.println(taskMarkTime);
//			if (taskMarkTime >= 600) {
//				List<WorkerRecordTrans> list1 = new ArrayList<>();
//				// 随机生成10个上传任务压入list1中
//				Set<Integer> set = new HashSet<Integer>();
//				double markTime = 0.00;
//				boolean panduan = true;
//				int m = 0;
//				while (true) {
//					m++;
//					//防止死循环
//					if(m > 100000){
//						break;
//					}
//					int z = (int) (Math.random() * (list2.size()+1));
//					//System.out.println(z);
//					panduan = set.add(z);// 检验重复数
//					if (!panduan || z >= list2.size()) {
//						continue;
//					} else {
//						if (list2.get(z).getTaskMarkTime() == 0) {
//							continue;
//						}
//						list1.add(list2.get(z));
//
//						markTime = markTime + Double.parseDouble(list2.get(z).getTaskMarkTime().toString());
//					}
//					//System.out.println(markTime);
//					if (markTime > 599) {
//						break;
//					}
//
//					// if (set.size() >= 10) {
//					// break;
//					// }
//				}
//				map.put("list", list1);
//			} else {
//				map.put("list", list2);
//			}
			List<WorkerRecordTrans> list3 = getListByPercent(list2,percent);
			map.put("list", list3);
		}
		return map;
	}

	/**
	 * 下载审核任务
	 * 
	 * @param list
	 * @param workerId
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/downAuditTask", method = RequestMethod.POST)
	@ResponseBody
	public  Map<String, Object> downAuditTaskPost(String list, int workerId, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<>();
		String url = request.getSession().getServletContext().getRealPath(Constants.SLASH);
		int userId = Integer.parseInt(request.getSession().getAttribute("userId").toString());
		url = url + "auditTemp";
		File f = new File(url);
		if (!f.exists()) {
			f.mkdir();
		}
		workerRecord workerRecord = workerRecordService.getWorkerRecordByWorkerId(workerId);
		SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATETIME);
		String packName = sdf.format(new Date()) + "_" + workerRecord.getUserName() + ".zip";
		List<taskWithBLOBs> list1 = new ArrayList<>();
		String taskId[] = list.split("_");
		for (int i = 0; i < taskId.length; i++) {
			taskWithBLOBs taskWithBLOBs = new taskWithBLOBs();
			taskWithBLOBs = taskService.selectByPrimaryKey(Integer.parseInt(taskId[i])); 
//			taskWithBLOBs = taskService.selectTaskForInspDownloadByTaskId(Integer.parseInt(taskId[i]));	// 外包商审核需要下载wav文件	
			list1.add(taskWithBLOBs);
		}
		int[] taskIdsInteger = new int[taskId.length];
		for (int j = 0; j < taskIdsInteger.length; j++) {
			taskIdsInteger[j] = Integer.parseInt(taskId[j]);
		}

		taskService.updateInspUseridByTaskId(taskIdsInteger,userId,1);
		
		
		
//		EmployerController employc = new EmployerController();
//		employc.downZIP(list1, packName, url, 0);
		
		inspectByWorkerDownZIP(list1, packName, url);
		
		// 项目在服务器上的远程绝对地址
		// String serverAndProjectPath = request.getLocalAddr() +
		// Constants.COLON + request.getLocalPort() + request.getContextPath();
		// 文件所谓的远程绝对路径
		// String wrongPath = Constants.HTTP + serverAndProjectPath +
		// Constants.SLASH + "auditTemp" + Constants.SLASH + packName;
		String wrongPath = Constants.SLASH + "auditTemp" + Constants.SLASH + packName;
		logger.debug("wrongPath:{}", wrongPath);
		map.put(Constants.WRONGPATH, wrongPath);
		return map;
	}

	/**
	 * 审核任务
	 * 
	 * @param taskEffective
	 * @param day
	 * @param workerId
	 * @param firstDate
	 * @param lastDate
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/auditing", method = RequestMethod.POST)
	@ResponseBody
	public  Map<String, Object> auditingPost(int taskEffective, int day, int workerId, HttpSession session, String note,
			int[] unqualifiedTaskIds,String uploadUUID, int sendBackType) {
		Map<String, Object> map = new HashMap<>();
		int userId = Integer.parseInt(session.getAttribute("userId").toString());
		if(uploadUUID.equals("undefined")){
			uploadUUID = null;
		}
		int inspectorrecordId = 0;
		//StackTraceElement[] items = Thread.currentThread().getStackTrace();
		//获得审核员id
		inspector ins = inspectorService.getinspectorByUserId(userId);
		int insId = 0;
		if(ins != null){
			insId = ins.getInspectorId();
		}else{
			insId = 0;
		}
		int m = 0;
		List<String> downPackNames = null;
		//保存初审审核有效时间 记录信息
		saveTheRecordOfInspectorMarkTimeForFirstInsp(ins.getInspectorId(), userId, ins.getInspectorName(),
				workerId, uploadUUID, sendBackType, unqualifiedTaskIds, taskEffective);
		if(taskEffective==0){
			//组装临时审核记录
			inspectorrecord irTemp = new inspectorrecord();
			irTemp.setInspectorid(userId);
			irTemp.setNote(note);
			downPackNames = workerRecordService.selectDownPackNamesByTaskIds(workerId,unqualifiedTaskIds);
			int[] workerIds = {workerId};
			//TODO  初审  不合格的时候添加不合格记录  当超过2次不合格的时候释放任务   调整成1次了 20181228
			int unqualifiedCountNum = workerRecordService.handleWithUnqualifiedCount(workerIds, null, 0, false,null,
					sendBackType,unqualifiedTaskIds,downPackNames,uploadUUID,null,insId,irTemp);
			if(unqualifiedCountNum==0){ // 如果unqualifiedCountNum为0 说明这次审核的所有任务都已经被释放  所以直接返回审核完成
				map.clear();
				map.put(Constants.REPLAY, 1);
				map.put(Constants.MESSAGE, "审核完成");
				return map;
			}
			m = taskService.updateAduitByWorkerId(workerId, taskEffective,downPackNames,uploadUUID,sendBackType,unqualifiedTaskIds);
		}
		AlipayInfo payInfo = null;
		if(m > 0||taskEffective==3){
			if(note.length()==0){
				note = "未填写";
			}
			if (taskEffective == 0 ) {
				inspectorrecord inspectorrecord = new inspectorrecord();
				inspectorrecord.setInspectorid(userId);
				inspectorrecord.setNote(note);
				inspectorrecord.setInspNum(m);
				inspectorRecordService.insertSelective(inspectorrecord);
				inspectorrecordId = inspectorRecordService.getMaxIdByInspectorId(userId);
			}
			if(taskEffective==3){
				taskService.updateAduitByWorkerIdForInspByUser(workerId, taskEffective, uploadUUID);  //更新质检时间
			}
			//获取计算工资节点
			int salaryCountTiming = 0;
//			List<VtdParameter> paramList = paramService.selectParamByType(Constants.SALARY_COUNT_TIMING);//查询结算设置用的参数 只有一条数据
//			if(!paramList.isEmpty()){
//				VtdParameter vp = paramList.get(0);
//				salaryCountTiming = Integer.parseInt(vp.getParamValue());
//			}
			List<VtdParameter> outsourcerCodeList = paramService.selectParamByType(Constants.OUTSOURCER_CODES);  //外包商组代码  数据库中只存一条信息  	
			VtdParameter param = outsourcerCodeList.get(0);
	    	String[] outsourcerCodes = param.getParamValue().split(",");
	    	worker w = workerService.selectByPrimaryKey(workerId);
	    	boolean flag = true;
		    for (int i = 0; i < outsourcerCodes.length; i++) {
				if (w.getWorkGroupCode().equals(outsourcerCodes[i])) {
					flag = false;  //审核的是外包工作者
				}
			}
			List<VtdParameter> paramList = null;
			if(flag){
				paramList = paramService.selectParamByType(Constants.SALARY_COUNT_TIMING);//查询结算设置用的参数 只有一条数据   自营
			}else{
				paramList = paramService.selectParamByType(Constants.OUTSOURCER_SALARY_COUNT_TIMING);//查询外包结算设置用的参数 只有一条数据  外包
			}
			if(!paramList.isEmpty()){
				VtdParameter vp = paramList.get(0);
				salaryCountTiming = Integer.parseInt(vp.getParamValue());
			}
			//插入工资单
			int salaryCountFlag = 0;  //是否计算工资标识  0 未计算   1已计算
			if(taskEffective == 3&&salaryCountTiming==1){    //当审核合格并且设置在初审计算工资是才向salary表插入数据
				payInfo = salaryService.insertTimer(workerId,uploadUUID);
				salaryCountFlag = 1;
				//初审更新工作记录中的finalMd5字段
				this.auditingUpdateFinalMd5(workerId, uploadUUID);
			}
			if(day>0){
				day = 3600*1000*day;
			}
			workerRecordService.updateAduitByWorkerId2(workerId, taskEffective, day, insId, inspectorrecordId, 
					downPackNames, salaryCountFlag, uploadUUID, sendBackType, unqualifiedTaskIds, payInfo);
		}else{
			map.clear();
			map.put(Constants.REPLAY, 0);
			map.put(Constants.MESSAGE, "审核失败!");
			return map;
		}		

		map.clear();
		map.put(Constants.REPLAY, 1);
		if(taskEffective==0){
			map.put(Constants.MESSAGE, "不合格任务退回完成");
		}else{
			//支付宝支付是否成功
			if(payInfo!=null){
				StringBuffer sbf = new StringBuffer();
				sbf.append("审核完成: ");
				sbf.append("  |  "+payInfo.getPayeeRealName());	
				if(payInfo.getIsSuccess()){
					sbf.append("的任务已通过支付宝成功支付  查询代码:  "+payInfo.getOutBizNo());	
				}else{
					sbf.append("支付宝支付失败, 可以在工资结算是一起结算      查询代码:  "+payInfo.getOutBizNo()+"  |  ");	
				}
				map.put(Constants.MESSAGE, sbf.toString());			
			}else{
				map.put(Constants.MESSAGE, "审核完成");			
			}
		}
		return map;
	}
	
	/**
	 * 按天检测
	 */
	@RequestMapping(value = "/inspectorByDay", method = RequestMethod.POST)
	@ResponseBody
	public  Map<String, Object> inspectorByDayPost(String dateCondition, String workGroupCode, int page, HttpSession session) {
		logger.debug("userName:{},timeMark:{}", dateCondition);
		Map<String, Object> map = new HashMap<String, Object>();
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String nowString = df.format(new Date());
		List<Map<String, Object>> list = workerRecordService.getListForInspectorByDay(dateCondition,page,Constants.ROW,workGroupCode, nowString);
		int count =  workerRecordService.getCountForInspectorByDay(dateCondition,workGroupCode,nowString);
		int totlePage = (int) Math.ceil((double) count / (double) Constants.ROW);
		map.put(Constants.LIST, list);
		map.put(Constants.TOTLE, count);
		map.put(Constants.TOTLE_PAGE, totlePage);
		map.put("searchTime", nowString);
		map.put("workGroupCode", workGroupCode);
		return map;
	}
	
	/**
	 * 巡检审核页
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/inspectorByDayList", method = RequestMethod.GET)
	public ModelAndView inspectorByDayListGet(String insDate, int percent, String searchTime, String workGroupCode, int inspectorId) {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("inspector/inspectorByDayList");
		mv.addObject("insDate", insDate);
		mv.addObject("percent", percent);
		mv.addObject("searchTime", searchTime);
		mv.addObject("workGroupCode", workGroupCode);
		List<VtdParameter> outsourcerCodeList = paramService.selectParamByType(Constants.OUTSOURCER_CODES);  //外包商组代码  数据库中只存一条信息  	
		VtdParameter param = outsourcerCodeList.get(0);
    	String[] outsourcerCodes = param.getParamValue().split(",");
    	boolean outsourcerFlag = false;
	    for (int i = 0; i < outsourcerCodes.length; i++) {
			if (workGroupCode.equals(outsourcerCodes[i])) {
				outsourcerFlag = true;  //审核的是外包工作者
			}
		}
	    mv.addObject("isOutsourcer", outsourcerFlag);
		mv.addObject("inspectorId", inspectorId);
		List<VtdParameter> errorTypeList = paramService.selectParamByType(Constants.ERROR_TYPE);
		mv.addObject("errorTypeList",errorTypeList);
		return mv;
	}

	/**
	 * 巡检审核页
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/inspectorByDayList", method = RequestMethod.POST)
	@ResponseBody
	public  Map<String, Object> inspectorByDayListPost(String insDate, int percent, String searchTime,String workGroupCode, int inspectorId, HttpSession session) {
		List<workerRecord> list = workerRecordService.getTaskForInspectorByDay(insDate,searchTime,workGroupCode,inspectorId);
		Map<String, Object> map = this.inspectorListCommon(list, percent);	
		return map;
	}
	
	/**
	 * 下载按天巡检审核任务   不带wav文件
	 * 
	 * @param list
	 * @param workerId
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/downAuditTaskForInspectByDay", method = RequestMethod.POST)
	@ResponseBody
	public  Map<String, Object> downAuditTaskForInspectByDayPost(String list, String insDate, HttpServletRequest request) {
		SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATETIME);
		int userId = Integer.parseInt(request.getSession().getAttribute("userId").toString());
		String packName = sdf.format(new Date()) + "_" + insDate + ".zip";
		String url = request.getSession().getServletContext().getRealPath(Constants.SLASH);
		Map<String, Object> map = this.downAuditTask(url, packName, list);
		String taskId[] = list.split("_");//根据下载任务的id更新task表中的对应字段数据
		int[] taskIdsInteger = new int[taskId.length];
		for (int j = 0; j < taskIdsInteger.length; j++) {
			taskIdsInteger[j] = Integer.parseInt(taskId[j]);
		}
		taskService.updateInspUseridByTaskId(taskIdsInteger,userId,2);
		return map;
	}
	
	/**
	 * 下载按天巡检审核任务   带wav文件
	 * 
	 * @param list
	 * @param workerId
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/downAuditTaskForInspectByDayWithWav", method = RequestMethod.POST)
	@ResponseBody
	public  Map<String, Object> downAuditTaskForInspectByDayWithWav(String list, String insDate, HttpServletRequest request) {
		SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATETIME);
		int userId = Integer.parseInt(request.getSession().getAttribute("userId").toString());
		String packName = sdf.format(new Date()) + "_" + insDate + "_withWav.zip";
		String url = request.getSession().getServletContext().getRealPath(Constants.SLASH);
		String taskId[] = list.split("_");//根据下载任务的id更新task表中的对应字段数据
		List<taskWithBLOBs> list1 = new ArrayList<>();
		for (int i = 0; i < taskId.length; i++) {
			taskWithBLOBs taskWithBLOBs = new taskWithBLOBs();
			taskWithBLOBs = taskService.selectByPrimaryKey(Integer.parseInt(taskId[i])); 
			list1.add(taskWithBLOBs);
		}
		this.inspectByWorkerDownZIP(list1, packName, url+ "auditTemp");
		Map<String, Object> map = new HashMap<>();
		String wrongPath = Constants.SLASH + "auditTemp" + Constants.SLASH + packName;
		logger.debug("wrongPath:{}", wrongPath);
		map.put(Constants.WRONGPATH, wrongPath);
		int[] taskIdsInteger = new int[taskId.length];
		for (int j = 0; j < taskIdsInteger.length; j++) {
			taskIdsInteger[j] = Integer.parseInt(taskId[j]);
		}
		taskService.updateInspUseridByTaskId(taskIdsInteger,userId,2);
		return map;
	}
	
	/**
	 * 按天巡检审核任务
	 * 
	 * @param taskEffective
	 * @param day
	 * @param workerId
	 * @param firstDate
	 * @param lastDate
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/auditingForInspectByDay", method = RequestMethod.POST)
	@ResponseBody
	public  Map<String, Object> auditingForInspectByDayPost(HttpSession session, String insDate, String searchTime, String workGroupCode, int inspectorId) {
		int taskEffective = 4; //审核通过后taskEffective值
		Map<String, Object> map = new HashMap<>();
		//查询审核通过的的任务id和工作记录id
		List<Map<String,Integer>> idMapList = workerRecordService.getTaskIdsAndWorkerrecordIdsforInspectByDay(insDate, searchTime, workGroupCode,inspectorId);    //查询需要更新的任务id和记录id
		List<Integer> recordIds = new ArrayList<Integer>();
		List<Integer> taskIds = new ArrayList<Integer>();
		if(!idMapList.isEmpty()){  
			for (Map<String,Integer> map2 : idMapList) {
				recordIds.add(map2.get("recordId"));
				taskIds.add(map2.get("taskId"));
			}
		}else{
			map.clear();
			map.put(Constants.REPLAY, 0);
			map.put(Constants.MESSAGE, "审核失败!");
			return map;
		}	
		int userId = Integer.parseInt(session.getAttribute("userId").toString());
		int inspectorrecordId = 0;
		//获取计算工资节点  
		int salaryCountTiming = 0;
		List<VtdParameter> outsourcerCodeList = paramService.selectParamByType(Constants.OUTSOURCER_CODES);  //外包商组代码  数据库中只存一条信息  	
		VtdParameter param = outsourcerCodeList.get(0);
    	String[] outsourcerCodes = param.getParamValue().split(",");
    	boolean flag = true;
	    for (int i = 0; i < outsourcerCodes.length; i++) {
			if (workGroupCode.equals(outsourcerCodes[i])) {
				flag = false;  //审核的是外包工作者
			}
		}
		List<VtdParameter> paramList = null;
		if(flag){
			paramList = paramService.selectParamByType(Constants.SALARY_COUNT_TIMING);//查询结算设置用的参数 只有一条数据   自营
		}else{
			paramList = paramService.selectParamByType(Constants.OUTSOURCER_SALARY_COUNT_TIMING);//查询外包结算设置用的参数 只有一条数据  外包
		}
		if(!paramList.isEmpty()){
			VtdParameter vp = paramList.get(0);
			salaryCountTiming = Integer.parseInt(vp.getParamValue());
		}
		List<AlipayInfo> payList = null;
		inspector ins = inspectorService.getinspectorByUserId(userId);
		int insId = 0;
		if(ins != null){
			insId = ins.getInspectorId();
		}else{
			insId = 0;
		}
		//TODO 巡审插入工资单   
		int salaryCountFlag = 0;  //是否计算工资标识  0 未计算   1已计算
		if(taskEffective == 4 && salaryCountTiming == 2){    //当审核合格并且设置在初审计算工资是才向salary表插入数据
			payList = salaryService.insertSalaryForInspByDay(insDate, searchTime, workGroupCode, recordIds);
			salaryCountFlag = 1;
			this.inspectByDayUpdateFinalMd5(recordIds);
		}else if(taskEffective == 0 && salaryCountTiming == 1){
			salaryCountFlag = 0; 
		}else{
			salaryCountFlag = 9;  //9  不更新
		}
		//保存巡审审核成功的有效时间
		saveTheRecordOfInspectorMarkTimeForSecondInsp(recordIds, ins.getInspectorId(), userId, ins.getInspectorName(), true);
		taskService.updateAduitForInspectByDay(taskIds, taskEffective);  
		workerRecordService.updateAduitForInspectByDay(insDate, taskEffective, 0, insId, inspectorrecordId, 
				null,searchTime, workGroupCode, salaryCountFlag, payList, recordIds);
		map.clear();
		map.put(Constants.REPLAY, 1);
		//支付宝支付是否成功
		StringBuffer sbf = new StringBuffer();
		if(payList!=null&&(!payList.isEmpty())){
			sbf.append("审核完成: ");
			for (AlipayInfo a : payList) {
				sbf.append("  |  "+a.getPayeeRealName());	
				if(a.getIsSuccess()){
					sbf.append("的任务已通过支付宝成功支付  查询代码:  "+a.getOutBizNo());	
				}else{
					sbf.append("支付宝支付失败, 可以在工资结算是一起结算      查询代码:  "+a.getOutBizNo()+"  |  ");	
				}
			}
			map.put(Constants.MESSAGE, sbf.toString());			
		}else{
			map.put(Constants.MESSAGE, "审核完成");			
		}
		return map;
	}
	
	/**
	 * 按包检测
	 * @param userName
	 * @param timeMark
	 * @param page
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/inspectorByPackage", method = RequestMethod.POST)
	@ResponseBody
	public  Map<String, Object> inspectorByPackagePost(String insPackageCondition, int page, HttpSession session) {
		logger.debug("userName:{},timeMark:{}", insPackageCondition);
		Map<String, Object> map = new HashMap<String, Object>();

		//查找已经完成的包来做检查  
		List<Integer> packList = workerRecordService.getPackIdForinspectorByPackage(); //找到已经通过按天核审的packid
//		List<Integer> packIds = new ArrayList<Integer>();
//		for (Iterator<Integer> iterator = packList.iterator(); iterator.hasNext();) {
//			Integer packId = (Integer) iterator.next();
//			// pack中的任务数 = (完成的任务数 + 无效任务数 )+ wav.length为0的数
//			if (taskService.getTaskCountByPackId(packId) == (workerRecordService.getTaskCountByPackIdForInspectorByPackage(packId) + taskService.getWorkerIdZeroCountByPackId(packId))) {
//				packIds.add(packId);
//			}
//		}
		if(packList.isEmpty()){
			map.put(Constants.LIST, "");
			map.put(Constants.TOTLE, 0);
			map.put(Constants.TOTLE_PAGE, 1);
			return map;
		}
		
		List<Map<String, Object>> list = workerRecordService.getListForInspectorByPackage(packList,insPackageCondition,page,Constants.ROW);
		int count =  workerRecordService.getCountForInspectorByPackage(packList, insPackageCondition);
		int totlePage = (int) Math.ceil((double) count / (double) Constants.ROW);
		map.put(Constants.LIST, list);
		map.put(Constants.TOTLE, count);
		map.put(Constants.TOTLE_PAGE, totlePage);
		return map;
	}
	
	/**
	 * 按包检查有效时间为0的任务检查
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/inspectorByPackageMarkTimeIsZero", method = RequestMethod.POST)
	public Map<String, Object>  iinspectorByPackageMarkTimeIsZeroGet(int packId, HttpSession session) {
		int taskEffective  = 1;
		Map<String, Object> map = new HashMap<>();
		List<Integer> taskIds = workerRecordService.getTaskIdsforInspectByPackageAndMarkTimeIsZero(packId,1);  //专用方法 只查询有效时间是0的记录
		int m = taskService.updateAduitForInspectByPackage(taskIds, taskEffective);
		if(m > 0){
			workerRecordService.updateAduitForInspectByPackageAndMarkTimeIsZero(packId, taskEffective, 0, 0, 0, 1); //专用方法 只修改有效时间是0的记录
		}else{
			map.clear();
			map.put(Constants.REPLAY, 0);
			map.put(Constants.MESSAGE, "审核失败!");
			return map;
		}		
		/**
		 * 查看任务包的任务完成情况,当任务数等于已完成时更新pack表的pack_status
		 */
		if (taskEffective == 1) {  // 放在包审核那
			// pack中的任务数 = (完成的任务数 + 无效任务数 )+ wav.length为0的数
			if (taskService.getTaskCountByPackId(packId) == (workerRecordService.getTaskCountByPackIdForInspectorByPackage(packId) + taskService.getWorkerIdZeroCountByPackId(packId))) {
				packWithBLOBs pack = new packWithBLOBs();
				pack.setPackId(packId);
				pack.setPackStatus(1);
				packService.updateByPrimaryKeySelective(pack);
			}
		}
		map.clear();
		map.put(Constants.REPLAY, 1);
		map.put(Constants.MESSAGE, "审核完成");
		return map;
	}
	
	/**
	 * 按包检查审核页
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/inspectorByPackageList", method = RequestMethod.GET)
	public ModelAndView inspectorByPackageListGet(int packId, int percent, String packName) {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("inspector/inspectorByPackageList");
		mv.addObject("packId", packId);
		mv.addObject("percent", percent);
		mv.addObject("packName", packName);
		List<VtdParameter> errorTypeList = paramService.selectParamByType(Constants.ERROR_TYPE);
		mv.addObject("errorTypeList",errorTypeList);
		return mv;
	}

	/**
	 * 按包检查审核页
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/inspectorByPackageList", method = RequestMethod.POST)
	@ResponseBody
	public  Map<String, Object> inspectorByPackageListPost(int packId, int percent,HttpSession session) {
		List<workerRecord> list = workerRecordService.getTaskForInspectorByPackage(packId);
		Map<String, Object> map = this.inspectorListCommon(list,percent);
		return map;
	}
	
	/**
	 * 下载按包审核任务
	 * 
	 * @param list
	 * @param workerId
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/downAuditTaskForInspectByPackage", method = RequestMethod.POST)
	@ResponseBody
	public  Map<String, Object> downAuditTaskForInspectByPackagePost(String list, String packName, HttpServletRequest request) {
		int userId = Integer.parseInt(request.getSession().getAttribute("userId").toString());
		SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATETIME);
		String pName = sdf.format(new Date()) + "_" + packName.replaceAll("/", "@") + ".zip";
		String url = request.getSession().getServletContext().getRealPath(Constants.SLASH);
		Map<String, Object> map = this.downAuditTask(url, pName, list);
		String taskId[] = list.split("_");   //根据下载任务的id更新task表中的对应字段数据
		int[] taskIdsInteger = new int[taskId.length];
		for (int j = 0; j < taskIdsInteger.length; j++) {
			taskIdsInteger[j] = Integer.parseInt(taskId[j]);
		}
		taskService.updateInspUseridByTaskId(taskIdsInteger,userId,3);
		return map;
	}
	
	/**
	 * 按包检测审核任务
	 * 
	 * @param taskEffective
	 * @param day
	 * @param workerId
	 * @param firstDate
	 * @param lastDate
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/auditingForInspectByPackage", method = RequestMethod.POST)
	@ResponseBody
	public  Map<String, Object> auditingForInspectByPackagePost(int taskEffective, int day, HttpSession session, 
				String note, int packId, int[] unqualifiedWorkerIds, int sendBackType, int[] unqualifiedTaskIds, String imgName) {
		Map<String, Object> map = new HashMap<>();
		int userId = Integer.parseInt(session.getAttribute("userId").toString());
		int inspectorrecordId = 0;
		//获取审核员id
		inspector ins = inspectorService.getinspectorByUserId(userId);
		int insId = 0;
		if(ins != null){
			insId = ins.getInspectorId();
		}else{
			insId = 0;
		}
		List<Integer> taskIds = workerRecordService.getTaskIdsforInspectByPackage(packId);
		int m = 0;
		if(taskEffective==0){
			//组装审核记录临时数据
			inspectorrecord irTemp = new inspectorrecord();
			irTemp.setInspectorid(userId);
			irTemp.setNote(note);
			irTemp.setImgName(imgName);
			salaryService.subtractFromSalaryForInspByPackage(unqualifiedWorkerIds, packId, sendBackType, unqualifiedTaskIds);    //将之前审核中已经计算过的时间从salary表中减掉
			//TODO 包审  不合格的时候添加不合格记录  当超过2次不合格的时候释放任务 调整成1次了 20181228
			int unqualifiedCountNum =workerRecordService.handleWithUnqualifiedCount(unqualifiedWorkerIds, null, packId, 
					false, null,sendBackType,unqualifiedTaskIds,null,null,null,insId,irTemp);
			if(unqualifiedCountNum==0){  // 如果unqualifiedCountNum为0 说明这次审核的所有任务都已经被释放  所以直接返回审核完成
				map.clear();
				map.put(Constants.REPLAY, 1);
				map.put(Constants.MESSAGE, "审核完成");
				if(unqualifiedTaskIds!=null){
					map.put("sendBackTaskIds", unqualifiedTaskIds);
				}
				return map;
			}
			m = taskService.updateAduitForInspectByPackageIsUnqualified(unqualifiedWorkerIds, packId, sendBackType, unqualifiedTaskIds);    //不合格退回  
		}else{
			m = taskService.updateAduitForInspectByPackage(taskIds, taskEffective);
		}
		List<AlipayInfo> payList = new ArrayList<AlipayInfo>();
		if(m > 0){
			if(note.length()==0){
				note = "未填写";
			}
			if (taskEffective == 0 ) {
				inspectorrecord inspectorrecord = new inspectorrecord();
				inspectorrecord.setInspectorid(userId);
				inspectorrecord.setNote(note);
				inspectorrecord.setInspNum(m);
				inspectorrecord.setImgName(imgName);
				inspectorRecordService.insertSelective(inspectorrecord);
				inspectorrecordId = inspectorRecordService.getMaxIdByInspectorId(userId);
			}
			
			//TODO  包审  插入工资单   
			int salaryCountFlag = 0;  //是否计算工资标识  0 未计算   1已计算
			if(taskEffective == 1){    //当审核合格并且设置在初审计算工资是才向salary表插入数据
				List<Integer> workerIds = workerRecordService.getWorkIdsByPackId(packId);
				for (Integer workerId : workerIds) {
					int salaryCountTiming = 0;
					List<VtdParameter> outsourcerCodeList = paramService.selectParamByType(Constants.OUTSOURCER_CODES);  //外包商组代码  数据库中只存一条信息  	
					VtdParameter param = outsourcerCodeList.get(0);
			    	String[] outsourcerCodes = param.getParamValue().split(",");
			    	worker w = workerService.selectByPrimaryKey(workerId);
			    	boolean flag = true;
				    for (int i = 0; i < outsourcerCodes.length; i++) {
						if (w.getWorkGroupCode().equals(outsourcerCodes[i])) {
							flag = false;  //审核的是外包工作者
						}
					}
					List<VtdParameter> paramList = null;
					if(flag){
						paramList = paramService.selectParamByType(Constants.SALARY_COUNT_TIMING);//查询结算设置用的参数 只有一条数据   自营
					}else{
						paramList = paramService.selectParamByType(Constants.OUTSOURCER_SALARY_COUNT_TIMING);//查询外包结算设置用的参数 只有一条数据  外包
					}
					if(!paramList.isEmpty()){
						VtdParameter vp = paramList.get(0);
						salaryCountTiming = Integer.parseInt(vp.getParamValue());
					}
					AlipayInfo payInfo = null;
					if(salaryCountTiming == 3){
						payInfo = salaryService.insertSalary(workerId,packId);
						salaryCountFlag = 1;
						this.inspectByPackageUpdateFinalMd5(workerId, packId);
					}else{
						salaryCountFlag = 9;  //9  不更新
					}
					if(payInfo!=null){
						payList.add(payInfo);
					}
				}
			}else if(taskEffective == 0){
				salaryCountFlag = 0;
			}else{
				salaryCountFlag = 9;  //9  不更新
			}
			if(day>0){
				day = 3600*1000*day;
			}
			workerRecordService.updateAduitForInspectByPackage(packId, taskEffective, day, insId, inspectorrecordId,
					unqualifiedWorkerIds, sendBackType, unqualifiedTaskIds,salaryCountFlag, payList);
		}else{
			map.clear();
			map.put(Constants.REPLAY, 0);
			map.put(Constants.MESSAGE, "审核失败!");
			return map;
		}		
		/**
		 * 查看任务包的任务完成情况,当任务数等于已完成时更新pack表的pack_status
		 */
		if (taskEffective == 1) {  // 放在包审核那
			// pack中的任务数 = (完成的任务数 + 无效任务数 )+ wav.length为0的数
			if (taskService.getTaskCountByPackId(packId) == (workerRecordService.getTaskCountByPackIdForInspectorByPackage(packId) + taskService.getWorkerIdZeroCountByPackId(packId))) {
				packWithBLOBs pack = new packWithBLOBs();
				pack.setPackId(packId);
				pack.setPackStatus(1);
				packService.updateByPrimaryKeySelective(pack);
			}
			
		}
//		//当任务完成时更新pack表的pack_status 
//		if (taskEffective == 1) { 
//			packWithBLOBs pack = new packWithBLOBs();
//			pack.setPackId(packId);
//			pack.setPackStatus(1);
//			packService.updateByPrimaryKeySelective(pack);
//	
//		}
		map.clear();
		map.put(Constants.REPLAY, 1);
		if(taskEffective==0){
			map.put(Constants.MESSAGE, "不合格任务退回完成");
			if(unqualifiedTaskIds!=null){
				map.put("sendBackTaskIds", unqualifiedTaskIds);
			}
		}else{
			//支付宝支付是否成功
			StringBuffer sbf = new StringBuffer();
			if(payList!=null&&(!payList.isEmpty())){
				sbf.append("审核完成: ");
				for (AlipayInfo a : payList) {
					sbf.append("  |  "+a.getPayeeRealName());	
					if(a.getIsSuccess()){
						sbf.append("的任务已通过支付宝成功支付  查询代码:  "+a.getOutBizNo());	
					}else{
						sbf.append("支付宝支付失败, 可以在工资结算是一起结算      查询代码:  "+a.getOutBizNo()+"  |  ");	
					}
				}
				map.put(Constants.MESSAGE, sbf.toString());			
			}else{
				map.put(Constants.MESSAGE, "审核完成");			
			}
		}
		return map;
	}
	
	/**
	 * 随机获取list中的数据
	 * @param list  源数据集合
	 * @param percent 百分比
	 * @return  根据百分比随机出的数据集合
	 */
	public static List<WorkerRecordTrans> getListByPercent(List<WorkerRecordTrans> list, int percent){
		//按页面选择百分比percent选出对应数量的数据 随机抽取不重复
		if(percent==100){
			return list;
		}else{
			long inspectNum = Math.round(list.size()*((double)percent/100));  //计算审核数量
			Set<Integer> set = new HashSet<Integer>();
			int breakFlag = 0;
			while(true){
				breakFlag++;
				set.add((int)(Math.random()*list.size()));   //范围为 0到任务总数的随机数 放入set中  set不保存重复数据
				if(set.size()==inspectNum){//当随机数的个数等于需要审核的任务数量时推出循环
					break;
				}
				if(breakFlag>100000){//防止死循环
					break;
				}
			}
			List<WorkerRecordTrans> list3 = new ArrayList<WorkerRecordTrans>();
			for (Integer i : set) {
				list3.add(list.get(i));//利用set中的随机数去出list2中的数据
			}
			return list3;
		}
	}
	
	/**
	 * 进入任务审核页面列表共同方法
	 * @param list
	 * @param percent  
	 * @return
	 */
	public Map<String, Object> inspectorListCommon(List<workerRecord> list, int percent){
		//处理查询条件
		String[] taskIds = new String[list.size()];
		for (int i = 0; i < list.size(); i++) {
			taskIds[i] = String.valueOf(list.get(i).getTaskId());
		}
		List<Integer> modifiedTaskIdList;
		if(taskIds.length!=0){
			//查询被修改过的任务的任务id
			modifiedTaskIdList = taskService.getModifiedTaskIds(taskIds);			
		}else{
			modifiedTaskIdList = null;
		}
		
		Map<String,Object> map = new HashMap<String, Object>();
		List<WorkerRecordTrans> list2 = new ArrayList<>();
		SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATETIME_FORMAT);
		Set<Integer> workeridSet = new HashSet<Integer>();//用于存放workerid的set  用set去掉重复数据
		double taskMarkTime = 0.00;
		for (Iterator<workerRecord> iterator = list.iterator(); iterator.hasNext();) {
			workerRecord workerRecord = (workerRecord) iterator.next();
			WorkerRecordTrans workerRecordTrans = new WorkerRecordTrans();			
			if(workerRecord.getTaskMarkTime() == 0){
				continue;
			}
			boolean isModified = false; //对比当前记录是否又被修改
			if(modifiedTaskIdList!=null&&modifiedTaskIdList.size()>0){
				for (Integer i : modifiedTaskIdList) {
					if(workerRecord.getTaskId().intValue()==i.intValue()){
						isModified = true;
					}
				}
			}
			if(isModified){
				String modifiedUsername = taskService.getLastModifiedUsernameByTaskid(workerRecord.getTaskId().intValue());
				workerRecordTrans.setTaskStatu(modifiedUsername);//为了页面显示临时存放   如果修改将最后一次修改该任务的用户的用户名显示在页面上
			}else{
				workerRecordTrans.setTaskStatu("-");//为了页面显示临时存放
			}
			workerRecordTrans.setTaskName(workerRecord.getTaskName().substring(0, workerRecord.getTaskName().lastIndexOf("@")));
			workerRecordTrans.setTaskId(workerRecord.getTaskId());
			workerRecordTrans.setWorkerRealName(workerRecord.getRealName());
			if(workerRecord.getTaskUploadTime() == null){
				workerRecordTrans.setTaskUploadTime(sdf.format(new Date()));
			}else{
				workerRecordTrans.setTaskUploadTime(sdf.format(workerRecord.getTaskUploadTime()));
			}	
			workerRecordTrans.setTaskMarkTime(workerRecord.getTaskMarkTime());
			workerRecordTrans.setWorkerId(workerRecord.getWorkerId());
			taskMarkTime = taskMarkTime + workerRecord.getTaskMarkTime();
			list2.add(workerRecordTrans);
			workeridSet.add(workerRecordTrans.getWorkerId());  //将workid添加进set中去除重复
		}
		map.clear();
		if (list2 == null || list2.size() == 0) {
			map.put("firstDate", "");
			map.put("lastDate", "");
			map.put("last", "");
			map.put("list", "");
		} else {
			map.put("firstDate", list2.get(0).getTaskUploadTime());
			map.put("lastDate", list2.get(list2.size() - 1).getTaskUploadTime());
			
			//按workerId获取随机数据
			List<WorkerRecordTrans> listForTheShow = new ArrayList<WorkerRecordTrans>();
			for (Integer workerId : workeridSet) { //循环set中的每一个workerId
				List<WorkerRecordTrans> listByWorkerId = new ArrayList<WorkerRecordTrans>();
				for (WorkerRecordTrans wrt : list2) {
					if(wrt.getWorkerId()==workerId){
						listByWorkerId.add(wrt); //当list2中的id等于set中当前循环的id时 添加到新的list中准备随机
					}
				}
				List<WorkerRecordTrans> list3 = getListByPercent(listByWorkerId,percent);
				listForTheShow.addAll(list3);//通过随机方式重新获取的list添加到页面展示list中
			}

//			List<WorkerRecordTrans> list3 = getListByPercent(list2,percent);
//			map.put("list", list3);
			map.put("list", listForTheShow);
		}
		return map;
	}
	
	/**
	 * 下载审核任务通用方法
	 * @param url
	 * @param packName
	 * @param taskIds
	 * @return
	 */
	public Map<String, Object> downAuditTask(String url, String packName, String taskIds){
		Map<String, Object> map = new HashMap<>();
		url = url + "auditTemp";
		File f = new File(url);
		if (!f.exists()) {
			f.mkdir();
		}
		List<taskWithBLOBs> list1 = new ArrayList<>();
		String taskId[] = taskIds.split("_");
		for (int i = 0; i < taskId.length; i++) {
			taskWithBLOBs taskWithBLOBs = new taskWithBLOBs();
//			taskWithBLOBs = taskService.selectByPrimaryKey(Integer.parseInt(taskId[i]));  将wav文件去掉    
			taskWithBLOBs = taskService.selectTaskForInspDownloadByTaskId(Integer.parseInt(taskId[i]));	
			list1.add(taskWithBLOBs);
		}

//		EmployerController employc = new EmployerController();  //原来的压缩包方法  
//		employc.downZIP(list1, packName, url, 0);
		
		List<Integer> modifiedTaskIdList = taskService.getModifiedTaskIds(taskId);
		inspectDownZIP(list1, packName, url, modifiedTaskIdList);    // 修改成下载的压缩包中审批修改过的文件单独存放在另一个文件夹中

		// 项目在服务器上的远程绝对地址
		// String serverAndProjectPath = request.getLocalAddr() +
		// Constants.COLON + request.getLocalPort() + request.getContextPath();
		// 文件所谓的远程绝对路径
		// String wrongPath = Constants.HTTP + serverAndProjectPath +
		// Constants.SLASH + "auditTemp" + Constants.SLASH + packName;
		String wrongPath = Constants.SLASH + "auditTemp" + Constants.SLASH + packName;
		logger.debug("wrongPath:{}", wrongPath);
		map.put(Constants.WRONGPATH, wrongPath);
		return map;
	}
	
	/**
	 * 快速审核  ---- 查找已经按人审核通过的包来进行快速审核  其实就是去掉了按天审核的步骤
	 * @param userName
	 * @param timeMark
	 * @param page
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/quickInspection", method = RequestMethod.POST)
	@ResponseBody
	public  Map<String, Object> quickInspectionPost(String quickInspCondition, int page, HttpSession session) {
		logger.debug("userName:{},timeMark:{}", quickInspCondition);
		Map<String, Object> map = new HashMap<String, Object>();
		//查询需要审核的包(已经按人审核完毕的任务)
		List<Integer> packList = workerRecordService.getPackageIdsForQuickInspection(quickInspCondition); //找到已经通过按人核审的packid
		//没有id就返回页面
		if(packList.isEmpty()){
			map.put(Constants.LIST, "");
			map.put(Constants.TOTLE, 0);
			map.put(Constants.TOTLE_PAGE, 1);
			return map;
		}
		//查询页面需要显示的数据
		List<Map<String, Object>> list = workerRecordService.getListForQuickInspection(packList,quickInspCondition,page,Constants.ROW);
		int count =  workerRecordService.getCountForInspectorByPackage(packList, quickInspCondition);
		int totlePage = (int) Math.ceil((double) count / (double) Constants.ROW);
		map.put(Constants.LIST, list);
		map.put(Constants.TOTLE, count);
		map.put(Constants.TOTLE_PAGE, totlePage);
		return map;
	}
	
	/**
	 * 快速审核页
	 * @return
	 */
	@RequestMapping(value = "/quickInspectionList", method = RequestMethod.GET)
	public ModelAndView quickInspectionListGet(int packId, int percent, String packName) {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("inspector/quickInspectionList");
		mv.addObject("packId", packId);
		mv.addObject("percent", percent);
		mv.addObject("packName", packName);
		return mv;
	}

	/**
	 * 快速审核页
	 * @return
	 */
	@RequestMapping(value = "/quickInspectionList", method = RequestMethod.POST)
	@ResponseBody
	public  Map<String, Object> quickInspectionListPost(int packId, int percent,HttpSession session) {
		List<workerRecord> list = workerRecordService.getTaskForQuickInspection(packId);
		Map<String, Object> map = this.inspectorListCommon(list,percent);
		return map;
	}
	
	/**
	 * 快速审核  审核任务
	 * @return
	 */
	@RequestMapping(value = "/auditingForQuickInspection", method = RequestMethod.POST)
	@ResponseBody
	public  Map<String, Object> auditingForQuickInspectionPost(int taskEffective, int day, HttpSession session, String note, int packId, int[] unqualifiedWorkerIds) {
		Map<String, Object> map = new HashMap<>();
		
		int userId = Integer.parseInt(session.getAttribute("userId").toString());
		int inspectorrecordId = 0;
		//获得审核员信息
		inspector ins = inspectorService.getinspectorByUserId(userId);
		int insId = 0;
		if(ins != null){
			insId = ins.getInspectorId();
		}else{
			insId = 0;
		}
		saveTheRecordOfInspectorMarkTimeForQuickInsp(packId, unqualifiedWorkerIds, taskEffective, ins.getInspectorId(), userId, ins.getInspectorName());
		List<Integer> taskIds = workerRecordService.getTaskIdsForQuickInspection(packId);
		int m = 0;
		if(taskEffective==0){
			//组装审核记录临时数据
			inspectorrecord irTemp = new inspectorrecord();
			irTemp.setInspectorid(userId);
			irTemp.setNote(note);
			salaryService.subtractFromSalaryForQuickInspection(unqualifiedWorkerIds, packId);   
			// 不合格的时候添加不合格记录  当超过2次不合格的时候释放任务  调整成1次了 20181228
			int unqualifiedCountNum =workerRecordService.handleWithUnqualifiedCount(unqualifiedWorkerIds, null, packId, true, 
					null,0,null,null,null,null,insId,irTemp);
			if(unqualifiedCountNum==0){  // 如果unqualifiedCountNum为0 说明这次审核的所有任务都已经被释放  所以直接返回审核完成
				map.clear();
				map.put(Constants.REPLAY, 1);
				map.put(Constants.MESSAGE, "审核完成");			
				return map;
			}
			m = taskService.updateAduitForQuickInspectionIsUnqualified(unqualifiedWorkerIds, packId);    //不合格退回  
		}else{
			m = taskService.updateAduitForInspectByPackage(taskIds, taskEffective);  //根据taskid更新数据没有添加别的判断条件用的还是包审核的语句
		}
		List<AlipayInfo> payList = new ArrayList<AlipayInfo>();
		if(m > 0){
			if(note.length()==0){
				note = "未填写";
			}
			if (taskEffective == 0) {
				inspectorrecord inspectorrecord = new inspectorrecord();
				inspectorrecord.setInspectorid(userId);
				inspectorrecord.setNote(note);
				inspectorrecord.setInspNum(m);
				inspectorRecordService.insertSelective(inspectorrecord);
				inspectorrecordId = inspectorRecordService.getMaxIdByInspectorId(userId);
			}
			
			//TODO 快速审核  插入工资单       
			int salaryCountFlag = 0;  //是否计算工资标识  0 未计算   1已计算
			if(taskEffective == 1){    //当审核合格并且设置在初审计算工资是才向salary表插入数据
				List<Integer> workerIds = workerRecordService.getWorkIdsByPackIdForQuickInspection(packId);  //  快速审核查询语句的查询条件应该是taskEffective=3的
				for (Integer workerId : workerIds) {
					int salaryCountTiming = 0;
					List<VtdParameter> outsourcerCodeList = paramService.selectParamByType(Constants.OUTSOURCER_CODES);  //外包商组代码  数据库中只存一条信息  	
					VtdParameter param = outsourcerCodeList.get(0);
			    	String[] outsourcerCodes = param.getParamValue().split(",");
			    	worker w = workerService.selectByPrimaryKey(workerId);
			    	boolean flag = true;
				    for (int i = 0; i < outsourcerCodes.length; i++) {
						if (w.getWorkGroupCode().equals(outsourcerCodes[i])) {
							flag = false;  //审核的是外包工作者
						}
					}
					List<VtdParameter> paramList = null;
					if(flag){
						paramList = paramService.selectParamByType(Constants.SALARY_COUNT_TIMING);//查询结算设置用的参数 只有一条数据   自营
					}else{
						paramList = paramService.selectParamByType(Constants.OUTSOURCER_SALARY_COUNT_TIMING);//查询外包结算设置用的参数 只有一条数据  外包
					}
					if(!paramList.isEmpty()){
						VtdParameter vp = paramList.get(0);
						salaryCountTiming = Integer.parseInt(vp.getParamValue());
					}
					AlipayInfo payInfo = null;
					if(salaryCountTiming != 1){
						payInfo = salaryService.insertSalaryForQuickInspection(workerId,packId);   //快速审核的工资表插入数据的条件也是taskEffective=3
						salaryCountFlag = 1;
						this.quickInspectionPosteUpdateFinalMd5(workerId, packId);
					}else{
						salaryCountFlag = 9;  //9  不更新
					}
					if(payInfo!=null){
						payList.add(payInfo);
					}
				}
			}else if(taskEffective == 0){//将之前审核中已经计算过的时间从salary表中减掉
				salaryCountFlag = 0;
			}else{
				salaryCountFlag = 9;  //9  不更新
			}
			if(day>0){
				day = 3600*1000*day;
			}
			workerRecordService.updateAduitForQuickInspection(packId, taskEffective, day, insId, inspectorrecordId,
					unqualifiedWorkerIds, salaryCountFlag, payList);
		}else{
			map.clear();
			map.put(Constants.REPLAY, 0);
			map.put(Constants.MESSAGE, "审核失败!");
			return map;
		}		
		/**
		 * 查看任务包的任务完成情况,当任务数等于已完成时更新pack表的pack_status
		 */
		if (taskEffective == 1) {  // 放在包审核那
			// pack中的任务数 = (完成的任务数 + 无效任务数 )+ wav.length为0的数
			if (taskService.getTaskCountByPackId(packId) == (workerRecordService.getTaskCountByPackIdForInspectorByPackage(packId) + taskService.getWorkerIdZeroCountByPackId(packId))) {
				packWithBLOBs pack = new packWithBLOBs();
				pack.setPackId(packId);
				pack.setPackStatus(1);
				packService.updateByPrimaryKeySelective(pack);
			}
			
		}
		map.clear();
		map.put(Constants.REPLAY, 1);
		if(taskEffective==0){
			map.put(Constants.MESSAGE, "不合格任务退回完成");
		}else{
			//支付宝支付是否成功
			StringBuffer sbf = new StringBuffer();
			if(payList!=null&&(!payList.isEmpty())){
				sbf.append("审核完成: ");
				for (AlipayInfo a : payList) {
					sbf.append("  |  "+a.getPayeeRealName());	
					if(a.getIsSuccess()){
						sbf.append("的任务已通过支付宝成功支付  查询代码:  "+a.getOutBizNo());	
					}else{
						sbf.append("支付宝支付失败, 可以在工资结算是一起结算      查询代码:  "+a.getOutBizNo()+"  |  ");	
					}
				}
				map.put(Constants.MESSAGE, sbf.toString());			
			}else{
				map.put(Constants.MESSAGE, "审核完成");			
			}
		}
		return map;
	}
	
	/**
	 * 快速审核有效时间为0的任务检查
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/quickInspectionMarkTimeIsZero", method = RequestMethod.POST)
	public Map<String, Object>  quickInspectionMarkTimeIsZeroPost(int packId, HttpSession session) {
		int taskEffective  = 1;
		Map<String, Object> map = new HashMap<>();
		List<Integer> taskIds = workerRecordService.getTaskIdsforInspectByPackageAndMarkTimeIsZero(packId,2);  //专用方法 只查询有效时间是0的记录
		int m = taskService.updateAduitForInspectByPackage(taskIds, taskEffective);
		if(m > 0){
			workerRecordService.updateAduitForInspectByPackageAndMarkTimeIsZero(packId, taskEffective, 0, 0, 0, 2); //专用方法 只修改有效时间是0的记录
		}else{
			map.clear();
			map.put(Constants.REPLAY, 0);
			map.put(Constants.MESSAGE, "审核失败!");
			return map;
		}		
		/**
		 * 查看任务包的任务完成情况,当任务数等于已完成时更新pack表的pack_status
		 */
		if (taskEffective == 1) {  // 放在包审核那
			// pack中的任务数 = (完成的任务数 + 无效任务数 )+ wav.length为0的数
			if (taskService.getTaskCountByPackId(packId) == (workerRecordService.getTaskCountByPackIdForInspectorByPackage(packId) + taskService.getWorkerIdZeroCountByPackId(packId))) {
				packWithBLOBs pack = new packWithBLOBs();
				pack.setPackId(packId);
				pack.setPackStatus(1);
				packService.updateByPrimaryKeySelective(pack);
			}
		}
		map.clear();
		map.put(Constants.REPLAY, 1);
		map.put(Constants.MESSAGE, "审核完成");
		return map;
	}
	
	/**
	 * 添加错误类型
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/addErrorType", method = RequestMethod.POST)
	public Map<String, Object> addErrorType(String errorTypeName, HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		
		int maxParamValueInteger = paramService.countAllByParamType(Constants.ERROR_TYPE);
		int paramValue = maxParamValueInteger+1;
		VtdParameter param = new VtdParameter();
		param.setParamName(errorTypeName);
		param.setParamValue(String.valueOf(paramValue));
		param.setParamType(Constants.ERROR_TYPE);
		param.setRemarks("审核不合格错误类型");
		param.setIsActive(true);
		int count = paramService.saveParameter(param);
		if(count == 1){
			map.put(Constants.REPLAY, 1);
			map.put(Constants.MESSAGE, "错误类型添加成功~!");
		}else{
			map.put(Constants.REPLAY, 0);
			map.put(Constants.MESSAGE, "错误类型添加失败,请联系系统维护人员!");
		}
		return map;
	}
	
	/**
	 * 检查错误类型是否重复
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/checkErrorType", method = RequestMethod.POST)
	public Map<String, Object> checkErrorType(String errorTypeName, HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		boolean flag = paramService.isParamExist(errorTypeName,Constants.ERROR_TYPE);
		if(!flag){
			map.put(Constants.REPLAY, 1);
			map.put(Constants.MESSAGE, "1");  //不存在
		}else{
			map.put(Constants.REPLAY, 0);
			map.put(Constants.MESSAGE, "0");  //存在
		}
		return map;
	}
	
	/**
	 * 检查错误类型是否重复
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/errorTypeList", method = RequestMethod.POST)
	public Map<String, Object> errorTypeList(HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put(Constants.REPLAY, 1);
		List<VtdParameter> list = paramService.selectAllParamByType(Constants.ERROR_TYPE);
		if(list.isEmpty()){
			map.put(Constants.LIST, "");
		}else{
			map.put(Constants.LIST, list);
		}
		Object obj = this.getNotice(session);
		map.put("notice", obj);
		return map;
	}
	
	/**
	 * 设置错误类型是否可用
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/changeErrorTypeActive", method = RequestMethod.POST)
	public Map<String, Object> changeErrorTypeActive(int errorTypeId, HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		int count = paramService.changeParamActiveById(errorTypeId);
		if(count==1){
			map.put(Constants.REPLAY, 1);
			map.put(Constants.MESSAGE, "1");
		}else{
			map.put(Constants.REPLAY, 0);
			map.put(Constants.MESSAGE, "0");
		}
		return map;
	}
	
	/**
	 * 修改错误类型
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/editErrorType", method = RequestMethod.POST)
	public Map<String, Object> editErrorType(int paramId, String errorTypeName, HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();	
		int count = paramService.updateParamNameById(paramId,errorTypeName);	
		if(count == 1){
			map.put(Constants.REPLAY, 1);
			map.put(Constants.MESSAGE, "错误类型修改成功~!");
		}else{
			map.put(Constants.REPLAY, 0);
			map.put(Constants.MESSAGE, "错误类型修改失败,请联系系统维护人员!");
		}
		return map;
	}
	
	@Autowired
	private MarkTimeMethodService markTimeMethodService;
	
	/**
	 * 审核上传修改的TAG和TextGrid
	 * 
	 * @param files
	 * @param session
	 * @param taskWithBLOBs
	 */
	@RequestMapping(value = "/inpsUpTagAndTextGrid", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> inpsUpTagAndTextGrid(@RequestParam("file") CommonsMultipartFile[] files, HttpSession session, taskWithBLOBs taskWithBLOBs, HttpServletRequest request, int[] taskIds) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<taskWithBLOBs> taskList = taskService.getTaskWithBLOBsByTaskIds(taskIds);
		Map<String,Integer> taskNameAndIds = new HashMap<String,Integer>();
		for (taskWithBLOBs tasktemp : taskList) {
//			taskNameAndIds.put(tasktemp.getTaskName().split("@")[0], tasktemp.getTaskId());
			taskNameAndIds.put(tasktemp.getTaskName().substring(0, tasktemp.getTaskName().lastIndexOf(Constants.POINT)), tasktemp.getTaskId());
		}
		
		int userId = (Integer)session.getAttribute(Constants.USER_ID);
		if (files.length == 0) {
			return null;
		}
		String uuid = UUID.randomUUID().toString().replaceAll("-", "");  //修改批次标记  修改一批使用同一个uuid
		List<Integer> returnList = new ArrayList<Integer>();
		long start = System.currentTimeMillis();
		int count = 0;
		for (int i = 0; i < files.length; i++) {
			String fileMD5 = DigestUtils.md5Hex(files[i].getBytes());
			boolean flag = false;  
			for (taskWithBLOBs task : taskList) {
				if(fileMD5.equals(DigestUtils.md5Hex(task.getTaskTextgrid()))){
					flag = true;   //如果上传文件和数据库中文件能匹配上 标记为true
					break;
				}
			}
			if(flag){
				continue;   //文件能匹配到 说明没有修改过 
			}else{
				
				//将上传文件的后缀修改为.wav来匹配map中的taksName 找到对应的task id 来更新数据
//				String nameWav = files[i].getOriginalFilename().substring(0, files[i].getOriginalFilename().lastIndexOf(Constants.POINT)) + Constants.POINT + Constants.WAV;
				String nameWav = files[i].getOriginalFilename().substring(0, files[i].getOriginalFilename().lastIndexOf(Constants.POINT));
				if(taskNameAndIds.get(nameWav)==null){ //如果为null说明上传文件不属于列表中的任务
					continue; 
				}
				int taskId = taskNameAndIds.get(nameWav);

				//获得修改文件的有效时间
				int packId = 0;
				int workerId = 0;
				for (taskWithBLOBs tasktemp : taskList) {
					if(taskId == tasktemp.getTaskId()){
						packId = tasktemp.getPackId();
						workerId = tasktemp.getWorkerId();
					}
				}
//				int packId = task.getPackId();
				markTimeMethod markTimeMethod = markTimeMethodService.getByPrimaryKey(packService.getTaskMarkTimeId(packId));
				String keyWords = "\"" + markTimeMethod.getKeywords() + "\"";
				double taskMarkTime = 0;
				InputStream is = null;
				try {
					is = files[i].getInputStream();
					TaskMarkTime tmt = new TaskMarkTime1();
					taskMarkTime = tmt.textGrid1(is, keyWords);
					if (taskMarkTime == 10000) {
						map.clear();
						map.put(Constants.REPLAY, 0);
						map.put(Constants.MESSAGE, "文件与包的时间统计方法不匹配,请联系管理员!");
						return map;
					}
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}finally{
					if(is != null){
						try {
							is.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
				// 更新task表 task操作表 worker_record表
				byte[] bytes = files[i].getBytes();
				taskWithBLOBs tempTask = new taskWithBLOBs();
				tempTask.setTaskTextgrid(bytes);
				tempTask.setTaskId(taskId);
				tempTask.setWorkerId(workerId);
				tempTask.setFaultId(userId);// 临时存放 不参与更新
				tempTask.setCreateMethod(uuid);   //临时存放 不参与更新
				tempTask.setTaskMarkTime(taskMarkTime);  //更新有效时间
				int returnTaskIs = taskService.modifyTaskTextgrid(tempTask);
				returnList.add(returnTaskIs);
				count++;
			}
		}
		long end = System.currentTimeMillis();
		System.out.println("共上传"+files.length+"个文件, 修改"+count+"个文件, 用时:"+(end-start)+"毫秒");
		boolean returnFlag = false;
		for (Integer i : returnList) {
			if(i==0){
				returnFlag = true;
			}
		}
		map.put(Constants.REPLAY, 1);
		if(returnList.isEmpty()){
			map.put("msg", "3");  //未更新文件
		}else if(returnFlag){
			map.put("msg", "2");  //有文件更新失败
		}else{
			map.put("msg", "1");  //成功
		} 
		map.put("returnList", returnList);
		return map;
	}
	
	/**
	 * 审核上传不合格任务错误图片
	 * @param files
	 * @param session
	 */
	@RequestMapping(value = "/inspPicUpload", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> inspPicUpload(HttpSession session,  HttpServletRequest request) {
 		Map<String, Object> map = new HashMap<String, Object>();
		String srcStr = request.getParameter("image").toString();
		if (srcStr.startsWith("data:image/png;base64,")||srcStr.startsWith("data:image/jpg;base64,")||srcStr.startsWith("data:image/bmp;base64,")) {
			  //处理截图 srcStr为base64字符串
			String picSuffix = srcStr.split(";")[0].split("/")[1];
			String base64 = "";
			if(srcStr.startsWith("data:image/png;base64,")){
				base64 = srcStr.replace("data:image/png;base64,", "");
			}else if(srcStr.startsWith("data:image/jpg;base64,")){
				base64 = srcStr.replace("data:image/jpg;base64,", "");
			}else if(srcStr.startsWith("data:image/bmp;base64,")){
				base64 = srcStr.replace("data:image/bmp;base64,", "");
			}
			byte[] b = null;  
	        if (base64 != null) {  
	            try {  
	                b = Base64.decodeBase64(base64);  
	            } catch (Exception e) {  
	                e.printStackTrace();  
	            }  
	        }
	        String url = request.getSession().getServletContext().getRealPath(Constants.SLASH);
	        int psIndex = url.lastIndexOf("ps");
	        url = url.substring(0, psIndex);
	        url = url + "uploadImages";
			File f = new File(url);
			if (!f.exists()) {
				f.mkdir();
			}
			String imgName = UUID.randomUUID().toString().replaceAll("-", "")+"."+picSuffix;
			
			try {
				// 创建一个文件输出流
				FileOutputStream out = new FileOutputStream(url + File.separator + imgName);
				out.write(b);
				// 关闭输出流
				out.close();
			} catch (Exception e) {
				e.printStackTrace();
				map.put("msg", 2); //上传失败  向服务器写入时出错
				//上传图片出现问题应该联系系统维护人员
			}
			map.put(Constants.REPLAY, 1);
			map.put("msg", 1); //上传成功
			map.put("imgSrc", "/uploadImages/"+imgName);
			map.put("imgName", imgName);
		} else {
			//上传图片出现问题应该联系系统维护人员
			map.put("msg", 3); //上传出错  接收到的字符串不是data:开头的这种形式 浏览器问题
		}
		return map;
	}
	
	/**
	 * 生成zip包--按天审核和按包审核用
	 * 
	 * @param list
	 * @param packName
	 * @param url  
	 * @param modifiedTaskIdList 被修改过的任务的id
	 * @return
	 */
	public int inspectDownZIP(List<taskWithBLOBs> list, String packName, String url, List<Integer> modifiedTaskIdList) {
		logger.debug("url:{}", packName);
		File zipFile = new File(url + Constants.SLASH + packName);
		if (zipFile.exists()) {
			zipFile.delete();
		}
		try {
			zipFile.createNewFile();
			FileOutputStream fos = new FileOutputStream(zipFile);
			ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos));

			// writeInZIP(list, zos, Constants.WAV,url);
			inspectWriteInZIP(list, zos, Constants.TAG, modifiedTaskIdList);
			inspectWriteInZIP(list, zos, Constants.TEXTGRID, modifiedTaskIdList);
			
			zos.close();// 不关闭,最后一个文件写入为0kb
			fos.flush();
			fos.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return 1;
	}
	
	/**
	 * 读取数据库文件,压入zip文件中 --按天审核和按包审核用
	 * 
	 * @param list
	 * @param zos
	 * @param fileType
	 * @param modifiedTaskIdList 被修改过的任务的id
	 */
	public void inspectWriteInZIP(List<taskWithBLOBs> list, ZipOutputStream zos, String fileType, List<Integer> modifiedTaskIdList) {
		for (Iterator<taskWithBLOBs> iterator = list.iterator(); iterator.hasNext();) {
			try {
				byte[] bufs = new byte[1024 * 10];
				taskWithBLOBs taskWithBLOBs = (taskWithBLOBs) iterator.next();
				String fileName = taskWithBLOBs.getTaskName() == null ? "Task.wav" : taskWithBLOBs.getTaskName();
				fileName = fileName.substring(0, fileName.lastIndexOf(Constants.POINT)) + Constants.POINT + fileType;
				// 创建ZIP实体,并添加进压缩包,按原目录结构
				ZipEntry zipEntry;
				//将taskid放在被修改任务id中循环对比检查是否有修改如果修改单独存放文件将爱
				boolean isModified = false;
				if(modifiedTaskIdList!=null&&modifiedTaskIdList.size()>0){
					for (Integer i : modifiedTaskIdList) {
						if(taskWithBLOBs.getTaskId().intValue()==i.intValue()){
							isModified = true;
						}
					}
				}
				
				if(isModified){
					zipEntry = new ZipEntry("modified file" + Constants.SLASH + taskWithBLOBs.getTaskDir() + Constants.SLASH + fileName);
				}else{
					zipEntry = new ZipEntry(taskWithBLOBs.getTaskDir() + Constants.SLASH + fileName);
				}
				zos.putNextEntry(zipEntry);
				byte[] data = null;
				if (fileType.equalsIgnoreCase(Constants.WAV)) {
					data = taskWithBLOBs.getTaskWav();
				} else if (fileType.equalsIgnoreCase(Constants.TAG)) {
					data = taskWithBLOBs.getTaskTag();
				} else if (fileType.equalsIgnoreCase(Constants.TEXTGRID)) {
					data = taskWithBLOBs.getTaskTextgrid();
				}
				if (data != null) {
					InputStream is = new ByteArrayInputStream(data);
					// 读取待压缩的文件并写进压缩包里
					BufferedInputStream bis = new BufferedInputStream(is, 1024);
					int read;
					while ((read = bis.read(bufs)) > 0) {
						zos.write(bufs, 0, read);//
					}
					bis.close();
					is.close();
				}

			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 生成zip包--按人审核用 需要加入wav下载
	 * 
	 * @param list
	 * @param packName
	 * @param url  
	 * @param modifiedTaskIdList 被修改过的任务的id
	 * @return
	 */
	public int inspectByWorkerDownZIP(List<taskWithBLOBs> list, String packName, String url) {
		logger.debug("url:{}", packName);
		File f = new File(url);
		if (!f.exists()) {
			f.mkdir();
		}
		File zipFile = new File(url + Constants.SLASH + packName);
		if (zipFile.exists()) {
			zipFile.delete();
		}
		try {
			zipFile.createNewFile();
			FileOutputStream fos = new FileOutputStream(zipFile);
			ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos));

			inspectByWorkerWriteInZIP(list, zos, Constants.WAV);
			inspectByWorkerWriteInZIP(list, zos, Constants.TAG);
			inspectByWorkerWriteInZIP(list, zos, Constants.TEXTGRID);
			
			zos.close();// 不关闭,最后一个文件写入为0kb
			fos.flush();
			fos.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return 1;
	}

	/**
	 * 按人审核  压入zip文件中
	 * 
	 * @param list
	 * @param zos
	 * @param fileType
	 */
	public void inspectByWorkerWriteInZIP(List<taskWithBLOBs> list, ZipOutputStream zos, String fileType) {
		for (Iterator<taskWithBLOBs> iterator = list.iterator(); iterator.hasNext();) {
			try {
				byte[] bufs = new byte[1024 * 10];
				taskWithBLOBs taskWithBLOBs = (taskWithBLOBs) iterator.next();
				String fileName = taskWithBLOBs.getTaskName() == null ? "Task.wav" : taskWithBLOBs.getTaskName();
				fileName = fileName.substring(0, fileName.lastIndexOf(Constants.POINT)) + Constants.POINT + fileType;
				// 创建ZIP实体,并添加进压缩包,按原目录结构
				ZipEntry zipEntry = new ZipEntry(taskWithBLOBs.getTaskDir() + Constants.SLASH + fileName);
				zos.putNextEntry(zipEntry);
				byte[] data = null;
				if (fileType.equalsIgnoreCase(Constants.WAV)) {
					data = taskWithBLOBs.getTaskWav();
				} else if (fileType.equalsIgnoreCase(Constants.TAG)) {
					data = taskWithBLOBs.getTaskTag();
				} else if (fileType.equalsIgnoreCase(Constants.TEXTGRID)) {
					data = taskWithBLOBs.getTaskTextgrid();
				}
				if (data != null) {
					InputStream is = new ByteArrayInputStream(data);
					// 读取待压缩的文件并写进压缩包里
					BufferedInputStream bis = new BufferedInputStream(is, 1024);
					int read;
					while ((read = bis.read(bufs)) > 0) {
						zos.write(bufs, 0, read);//
					}
					bis.close();
					is.close();
				}

			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 审核员--查看工作者标注时间
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/queryInspectorMarkTimeList", method = RequestMethod.POST)
	public Map<String, Object>  queryInspectorMarkTimeListPost(int page, int dateType, String beginDate, String endDate,
			String nameCondition, HttpSession session) {
		String workGroupCode = session.getAttribute("workGroup").toString();
		Map<String, Object> map = new HashMap<>();
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		int totlePage = Constants.ZERO;
		List<Map<String, Object>> salaryList = salaryService.getSalary(dateType, page, Constants.ROW, beginDate, endDate, nameCondition, 0, 2, workGroupCode);
		if (salaryList == null) {
			map.put(Constants.LIST, "");
			return map;
		}
		//获取计算工资节点  
		int salaryCountTiming = 0;
		List<VtdParameter> outsourcerCodeList = paramService.selectParamByType(Constants.OUTSOURCER_CODES);  //外包商组代码  数据库中只存一条信息  	
		VtdParameter param = outsourcerCodeList.get(0);
		String[] outsourcerCodes = param.getParamValue().split(",");
		boolean flag = true;
		for (int i = 0; i < outsourcerCodes.length; i++) {
			if (workGroupCode.equals(outsourcerCodes[i])) {
				flag = false;  //审核的是外包工作者
			}
		}
		List<VtdParameter> paramList = null;
		if(flag){
			paramList = paramService.selectParamByType(Constants.SALARY_COUNT_TIMING);//查询结算设置用的参数 只有一条数据   自营
		}else{
			paramList = paramService.selectParamByType(Constants.OUTSOURCER_SALARY_COUNT_TIMING);//查询外包结算设置用的参数 只有一条数据  外包
		}
		if(!paramList.isEmpty()){
			VtdParameter vp = paramList.get(0);
			salaryCountTiming = Integer.parseInt(vp.getParamValue());
		}
		Double d = 0.00;
		for (Iterator<Map<String, Object>> iterator = salaryList.iterator(); iterator.hasNext();) {
			Map<String, Object> map2 = (Map<String, Object>) iterator.next();
			if (map2.get("markTime") == null) {
				map2.put("markTimeHours", 0.00);
				map2.put("salary", 0);
			} else {
				d = Double.parseDouble(map2.get("markTime").toString());
				if (d < 0) {
					map2.put("markTimeHours", -d/3600);
					map2.put("sec", Math.round(-d));
				} else {
					map2.put("markTimeHours", d/3600);
					map2.put("sec", Math.round(d));
				}
//				map2.put("salary", Math.round(Double.parseDouble(map2.get("salaryValue").toString())));
				//根据工资计算节点的不同 获取未审核时间 
				double aduiting = workerRecordService.getTaskMarkTimeForUninspection(Integer.parseInt(map2.get("workerId").toString()),salaryCountTiming);
				map2.put("aduiting", aduiting);
				map2.put("aduitingHours", aduiting/3600);
			}
			list.add(map2);
		}
		map.clear();
		int totle = salaryService.getSalary100Count(dateType, beginDate, endDate, nameCondition, 0, 2, workGroupCode);
		totlePage = (int) Math.ceil((double) totle / (double) Constants.ROW);
		map.put(Constants.LIST, list);
		map.put(Constants.TOTLE, totle);
		map.put(Constants.TOTLE_PAGE, totlePage);
		return map;
	}	
	
	/**
	 * 初审审核有效时间为0的任务检查
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/inspectionByWorkerMarkTimeIsZero", method = RequestMethod.POST)
	public Map<String, Object>  inspectionByWorkerMarkTimeIsZero(int workerId, String uploadUUID, HttpSession session) {
		Map<String, Object> map = new HashMap<>();
		int userId = Integer.parseInt(session.getAttribute("userId").toString());
		//获得审核员id
		inspector ins = inspectorService.getinspectorByUserId(userId);
		int insId = 0;
		if(ins != null){
			insId = ins.getInspectorId();
		}else{
			insId = 0;
		}
		//获取计算工资节点
		int salaryCountTiming = 0;
		List<VtdParameter> outsourcerCodeList = paramService.selectParamByType(Constants.OUTSOURCER_CODES);  //外包商组代码  数据库中只存一条信息  	
		VtdParameter param = outsourcerCodeList.get(0);
    	String[] outsourcerCodes = param.getParamValue().split(",");
    	worker w = workerService.selectByPrimaryKey(workerId);
    	boolean flag = true;
	    for (int i = 0; i < outsourcerCodes.length; i++) {
			if (w.getWorkGroupCode().equals(outsourcerCodes[i])) {
				flag = false;  //审核的是外包工作者
			}
		}
		List<VtdParameter> paramList = null;
		if(flag){
			paramList = paramService.selectParamByType(Constants.SALARY_COUNT_TIMING);//查询结算设置用的参数 只有一条数据   自营
		}else{
			paramList = paramService.selectParamByType(Constants.OUTSOURCER_SALARY_COUNT_TIMING);//查询外包结算设置用的参数 只有一条数据  外包
		}
		if(!paramList.isEmpty()){
			VtdParameter vp = paramList.get(0);
			salaryCountTiming = Integer.parseInt(vp.getParamValue());
		}
		if(salaryCountTiming==1){    
			//初审更新工作记录中的finalMd5字段
			this.auditingUpdateFinalMd5(workerId, uploadUUID);
		}
		boolean isSuccess = workerRecordService.inspectionByWorkerMarkTimeIsZero(workerId, uploadUUID, insId);
		if(isSuccess){
			map.put(Constants.REPLAY, 1);
			map.put(Constants.MESSAGE, "审核完成");
			return map;
		}else{
			map.put(Constants.REPLAY, 0);
			map.put(Constants.MESSAGE, "审核失败!");
			return map;
		}		
	}
	
	/**
	 * 按天巡检审核任务----不合格退回
	 * @param day                  退回时间  单位小时
	 * @param session          	   session
	 * @param note                 错误原因
	 * @param insDate              初审审核日期
	 * @param inspectedTaskIds     审核过的任务id 不一定是全部批次任务的id
	 * @param unqualifiedTaskIds   不合格的任务id
	 * @param searchTime           审核时点击查询的时间
	 * @param workGroupCode        工作组代码
	 * @param inspectorId          初审审核员id
	 * @return
	 */
	@RequestMapping(value = "/sendBackForInspectByDay", method = RequestMethod.POST)
	@ResponseBody
	public  Map<String, Object> sendBackForInspectByDayPost(int day, HttpSession session, HttpServletRequest request,
			String note, String insDate, String inspectedTaskIds, int[] unqualifiedTaskIds, String searchTime, String workGroupCode, int inspectorId) {
		Map<String, Object> map = new HashMap<>();
		//查询审核通过的的任务id和工作记录id
		// taskList审核的任务id   unqualifiedTaskIds不合格的任务 id  taskIds 被退回的全部任务
		List<Map<String,Integer>> idMapList = workerRecordService.getTaskIdsAndWorkerrecordIdsforInspectByDay(insDate, searchTime, workGroupCode, inspectorId);    //查询需要更新的任务id和记录id
		List<Integer> recordIds = new ArrayList<Integer>();
		List<Integer> taskIds = new ArrayList<Integer>();
		if(!idMapList.isEmpty()){  
			for (Map<String,Integer> map2 : idMapList) {
				recordIds.add(map2.get("recordId"));
				taskIds.add(map2.get("taskId"));
			}
		}else{
			map.clear();
			map.put(Constants.REPLAY, 0);
			map.put(Constants.MESSAGE, "审核失败!");
			return map;
		}	
		//巡审退回批次UUID
		String inspectionSendbackUUID = UUID.randomUUID().toString().toUpperCase().replace("-", "");
		int userId = Integer.parseInt(session.getAttribute("userId").toString());
	    //审核记录信息
	    StringBuilder taskIdsSB = new StringBuilder();
	    for (int i = 0; i < unqualifiedTaskIds.length; i++) {
			if(i == 0){
				taskIdsSB.append(String.valueOf(unqualifiedTaskIds[i]));
			}else{
				taskIdsSB.append("_"+String.valueOf(unqualifiedTaskIds[i]));
			}
		}
	    inspector ins = inspectorService.getinspectorByUserId(userId);
		int insId = 0;
		if(ins != null){
			insId = ins.getInspectorId();
		}else{
			insId = 0;
		}
		//保存巡审审核成功的有效时间
		saveTheRecordOfInspectorMarkTimeForSecondInsp(recordIds, ins.getInspectorId(), userId, ins.getInspectorName(), false);
		//保存审核记录
		InspectorRecordWithBLOBs record = new InspectorRecordWithBLOBs();
		record.setInspectorid(insId);
		record.setNote(note);
		record.setInspNum(recordIds.size());
		record.setInspectionSendbackUUID(inspectionSendbackUUID);
		record.setInspectedTaskIds(inspectedTaskIds);
		record.setUnqualifiedTaskIds(taskIdsSB.toString());
		inspectorRecordService.saveInspectorRecordWithBLOBs(record);
		int inspectorRecordId = inspectorRecordService.getMaxIdByInspectorId(userId);
		List<VtdParameter> outsourcerCodeList = paramService.selectParamByType(Constants.OUTSOURCER_CODES);  //外包商组代码  数据库中只存一条信息  	
		VtdParameter param = outsourcerCodeList.get(0);
    	String[] outsourcerCodes = param.getParamValue().split(",");
    	boolean outsourcerFlag = false;
	    for (int i = 0; i < outsourcerCodes.length; i++) {
			if (workGroupCode.equals(outsourcerCodes[i])) {
				outsourcerFlag = true;  //审核的是外包工作者
			}
		}
	    List<VtdParameter> sendbackCountList = paramService.selectParamByType(Constants.INSPECTION_SECOND_TO_FIRST_SENDBACK_COUNT); //巡审退回至初审次数  数据库中只存一条信息  	
	    VtdParameter param2 = sendbackCountList.get(0 );
	    int sendbackCount = Integer.parseInt(param2.getParamValue());
		if(outsourcerFlag){  //退回给外包商有次数限制超过次数就回收   
			// 不合格的时候添加不合格记录  当超过2次不合格的时候释放任务
			int releaseNum = workerRecordService.countReleaseTaskNum(recordIds, sendbackCount);
			boolean releaseFlag = false;
			if(releaseNum>0){
				this.saveSendbackTasksToServer(taskIds, inspectionSendbackUUID, request);
				releaseFlag= true;
			}
			//释放超过返回次数的任务 没超过的sendbackCount加1
			int num = workerRecordService.modifySendbackCountAndReleaseTask(recordIds,taskIds,releaseFlag,inspectionSendbackUUID,inspectorRecordId,userId);
			if(num==0){  // 如果unqualifiedCountNum为0 说明这次审核的所有任务都已经被释放  所以直接返回审核完成
				map.clear();
				map.put(Constants.REPLAY, 1);
				map.put(Constants.MESSAGE, "审核完成,不合格任务已被系统回收.");			
				return map;
			}
			//			根据工作组代码将工作组内的下载锁定
			paramService.updateBackup1ByParamValueAndParamType(workGroupCode, Constants.WORK_GROUP, Constants.LOCK);
			day = 3600*1000*day;
		}else{
			day = 0;
		}
		if(note.length()==0){
			note = "未填写";
		}
		
		workerRecordService.updateInspectByDaySendbackWrokerRecords(recordIds,inspectorRecordId,inspectionSendbackUUID,day);
		map.clear();
		map.put(Constants.REPLAY, 1);
		map.put(Constants.MESSAGE, "不合格任务退回完成");
		return map;
	}
	
	/**
	 * 审核员页面 被退回列表
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/querySendbackList", method = RequestMethod.POST)
	public Map<String, Object> querySendbackListPost(HttpSession session) {
		Map<String, Object> map = new HashMap<>();
		int userId = Integer.parseInt(session.getAttribute("userId").toString());
		inspector ins = inspectorService.getinspectorByUserId(userId);
		//检查是否是外包商
		String workGroupCode = session.getAttribute("workGroup").toString();
		List<VtdParameter> outsourcerCodeList = paramService.selectParamByType(Constants.OUTSOURCER_CODES);  //外包商组代码  数据库中只存一条信息  	
		VtdParameter param = outsourcerCodeList.get(0);
    	String[] outsourcerCodes = param.getParamValue().split(",");
    	boolean outsourcerFlag = false;
	    for (int i = 0; i < outsourcerCodes.length; i++) {
			if (workGroupCode.equals(outsourcerCodes[i])) {
				outsourcerFlag = true;  //是外包商
			}
		}
	    List<VtdParameter> sendbackCountList = paramService.selectParamByType(Constants.INSPECTION_SECOND_TO_FIRST_SENDBACK_COUNT); //巡审退回至初审次数  数据库中只存一条信息  	
	    VtdParameter param2 = sendbackCountList.get(0 );
	    int sendbackCountLimit = Integer.parseInt(param2.getParamValue());
	    //查询数据
	    List<Map<String,Object>> list = workerRecordService.querySendbackListByInspectorId(ins.getInspectorId());
		long nowTimeMsec = new Date().getTime();  //现在时间的毫秒数
		for (Map<String, Object> map2 : list) {
			if(outsourcerFlag){  //外包有时间限制  自营没有
				Date sendbackDate = (Date)map2.get("sendbackTime");
				long endMsec = sendbackDate.getTime()+Long.parseLong(map2.get("timeLimit").toString());
				if(endMsec > nowTimeMsec){//未超时
					map2.put("timeoutFlag", false);
					map2.put("endMsec", endMsec);
				}else if(endMsec < nowTimeMsec){ //已超时   正常超时的话会被回收
					map2.put("timeoutFlag", true);
					map2.put("endMsec", 0);
				}else{ //正好相等 也是有可能的  基本就被回收了
					map2.put("timeoutFlag", true);
					map2.put("endMsec", 0);
				}
				map2.put("ableModifyCount", sendbackCountLimit-Integer.parseInt(map2.get("sendbackCount").toString())+1);
				map2.put("outsourcerFlag", outsourcerFlag);
			}else{
				map2.put("outsourcerFlag", outsourcerFlag);
				map2.put("ableModifyCount", "无限制");
			}
		}
		if(list.isEmpty()){
			map.put(Constants.LIST, "");
		}else{
			map.put(Constants.LIST, list);
		}
		return map;
	}
	
	/**
	 * 初审打开被退回列表
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/sendbackInspectorList", method = RequestMethod.GET)
	public ModelAndView sendbackInspectorListGet(String sendbackUUID, int inspectorId, int inspectorRecordId) {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("inspector/sendbackInspectorList");
		mv.addObject("sendbackUUID", sendbackUUID);
		mv.addObject("inspectorId", inspectorId);
		mv.addObject("inspectorRecordId", inspectorRecordId);
		return mv;
	}
	
	/**
	 * 初审打开被退回列表
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/sendbackInspectorList", method = RequestMethod.POST)
	public Map<String, Object> sendbackInspectorListPost(String sendbackUUID, int inspectorId, int inspectorRecordId, HttpSession session) {
		Map<String, Object> map = new HashMap<>();
		DateFormat df = new SimpleDateFormat(Constants.DATETIME_FORMAT);
		InspectorRecordWithBLOBs inspRecord = inspectorRecordService.selectWithBLOBsByPrimaryKey(inspectorRecordId);
		String sendbackReason = inspRecord.getNote();
		String[] inspectedTaskIds = inspRecord.getInspectedTaskIds().split("_");
		String[] unqualifiedTaskIds = inspRecord.getUnqualifiedTaskIds().split("_");
		//处理页面显示信息
		List<workerRecord> list = workerRecordService.querySendbackWorkerRecordBySendbackUUID(sendbackUUID,inspectorId);
		List<Map<String,Object>> listForShow = new ArrayList<Map<String,Object>>();
		for (workerRecord w : list) {
			int taskId = w.getTaskId();
			Map<String, Object> temp = new HashMap<>();
			temp.put("realName", w.getRealName());
			
			temp.put("taskName", w.getTaskName().substring(0, w.getTaskName().lastIndexOf("@")));
			temp.put("taskMarkTime", w.getTaskMarkTime());
			temp.put("sendbackTime", df.format(w.getTaskOverTime()));
			temp.put("taskId", taskId);
			//将审核过的任务和不合格的任务 分别作出标记
			for (int i = 0; i < unqualifiedTaskIds.length; i++) {
				if(taskId == Integer.valueOf(unqualifiedTaskIds[i])){
					temp.put("isUnqualified", true);
					break;
				}else{
					temp.put("isUnqualified", false);
				}
			}
			for (int i = 0; i < inspectedTaskIds.length; i++) {
				if(taskId == Integer.valueOf(inspectedTaskIds[i])){
					temp.put("isInspected", true);
					break;
				}else{
					temp.put("isInspected", false);
				}
			}
			listForShow.add(temp);
		}
		int inspectedNum = inspectedTaskIds.length;
		int unqualifiedNum = unqualifiedTaskIds.length;
		map.put("inspectedNum", inspectedNum);
		map.put("unqualifiedNum", unqualifiedNum);
		map.put("list", listForShow);
		map.put("sendbackReason", sendbackReason);
		return map;
	}
	
	/**
	 * 下载被巡审退回任务
	 * 
	 * @param list
	 * @param workerId
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/downloadSendbackTasks", method = RequestMethod.POST)
	@ResponseBody
	public  Map<String, Object> downloadSendbackTasks(String list, String sendbackUUID, HttpServletRequest request) {
		int userId = Integer.parseInt(request.getSession().getAttribute("userId").toString());
		SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATETIME);
		String pName = sdf.format(new Date()) + "_" + sendbackUUID + ".zip";
		String url = request.getSession().getServletContext().getRealPath(Constants.SLASH);
//		Map<String, Object> map = this.downAuditTask(url, pName, list);
		String taskId[] = list.split("_");
		List<taskWithBLOBs> list1 = new ArrayList<>();
		for (int i = 0; i < taskId.length; i++) {
			taskWithBLOBs taskWithBLOBs = new taskWithBLOBs();
			taskWithBLOBs = taskService.selectByPrimaryKey(Integer.parseInt(taskId[i])); 
			list1.add(taskWithBLOBs);
		}
		this.inspectByWorkerDownZIP(list1, pName, url+"auditTemp");
		Map<String, Object> map = new HashMap<String, Object>();
		String wrongPath = Constants.SLASH + "auditTemp" + Constants.SLASH + pName;
		map.put(Constants.WRONGPATH, wrongPath);
		int[] taskIdsInteger = new int[taskId.length];//根据下载任务的id更新task表中的对应字段数据
		for (int j = 0; j < taskIdsInteger.length; j++) {
			taskIdsInteger[j] = Integer.parseInt(taskId[j]);
		}
		taskService.updateInspUseridByTaskId(taskIdsInteger,userId,1);
		return map;
	}
	
	/**
	 * 退回任务修改完成
	 * @return
	 */
	@RequestMapping(value = "/modifyCompleted", method = RequestMethod.POST)
	@ResponseBody
	public  Map<String, Object> modifyCompleted(String sendbackUUID, int inspectorId, HttpServletRequest request, HttpSession session) {
		Map<String, Object> map = new HashMap<>();
		String workGroupCode = session.getAttribute(Constants.WORK_GROUP).toString();
		int count = workerRecordService.updateWorkerRecordForModifyCompleted(sendbackUUID,inspectorId);
		int WaitInspModificationNum = workerRecordService.queryWaitInspModificationNumByWorkGroupCode(workGroupCode);
		if(WaitInspModificationNum==0){
			//根据工作组代码将工作组内的下载锁定解锁
			paramService.updateBackup1ByParamValueAndParamType(workGroupCode, Constants.WORK_GROUP, Constants.UNLOCK);
		}
		if(count==0){
			map.put(Constants.REPLAY, 0);
			map.put(Constants.MESSAGE, "提交失败,请联系管理人员!");
		}else{
			map.put(Constants.REPLAY, 1);
			map.put(Constants.MESSAGE, "提交成功");
		}
		return map;
	}
	
	/**
	 * 初审修改完成列表查询
	 * @return
	 */
	@RequestMapping(value = "/queryModifyCompletedList", method = RequestMethod.POST)
	@ResponseBody
	public  Map<String, Object> queryModifyCompletedList(HttpSession session) {
		Map<String, Object> map = new HashMap<>();
		DateFormat df = new SimpleDateFormat(Constants.DATETIME_FORMAT);
		List<VtdParameter> sendbackCountList = paramService.selectParamByType(Constants.INSPECTION_SECOND_TO_FIRST_SENDBACK_COUNT); //巡审退回至初审次数  数据库中只存一条信息  	
		VtdParameter param2 = sendbackCountList.get(0 );
		int sendbackCountLimit = Integer.parseInt(param2.getParamValue());
	    //查询数据
	    List<Map<String,Object>> list = workerRecordService.queryModifyCompletedList();
	    for (Map<String, Object> map2 : list) {
			map2.put("modifyCompletedTime", df.format(map2.get("modifyCompletedTime")));
			map2.put("ableModifyCount", sendbackCountLimit-Integer.parseInt(map2.get("sendbackCount").toString())+1);
		}
		if(list.isEmpty()){
			map.put(Constants.LIST, "");
		}else{
			map.put(Constants.LIST, list);
		}
		return map;
	
	}
	
	/**
	 * 巡审打开初审修改完成任务列表
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/modifyCompletedInspectorList", method = RequestMethod.GET)
	public ModelAndView modifyCompletedInspectorListGet(String sendbackUUID, int inspectorId, 
			int inspectorRecordId, int percent, String workGroupCode) {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("inspector/modifyCompletedInspectorList");
		mv.addObject("sendbackUUID", sendbackUUID);
		mv.addObject("inspectorId", inspectorId);
		mv.addObject("percent", percent);
		mv.addObject("inspectorRecordId", inspectorRecordId);
		mv.addObject("workGroupCode",workGroupCode);
		List<VtdParameter> outsourcerCodeList = paramService.selectParamByType(Constants.OUTSOURCER_CODES);  //外包商组代码  数据库中只存一条信息  	
		VtdParameter param = outsourcerCodeList.get(0);
    	String[] outsourcerCodes = param.getParamValue().split(",");
    	boolean outsourcerFlag = false;
	    for (int i = 0; i < outsourcerCodes.length; i++) {
			if (workGroupCode.equals(outsourcerCodes[i])) {
				outsourcerFlag = true;  //审核的是外包工作者
			}
		}
	    mv.addObject("isOutsourcer", outsourcerFlag);
		return mv;
	}
	
	/**
	 * 巡审打开初审修改完成任务列表
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/modifyCompletedInspectorList", method = RequestMethod.POST)
	public Map<String, Object> modifyCompletedInspectorListPost(String sendbackUUID, int inspectorId, int inspectorRecordId, 
			int percent, HttpSession session) {
		//查询列表信息
		List<workerRecord> list = workerRecordService.queryModifyCompletedWorkerRecordBySendbackUUID(sendbackUUID,inspectorId);
		Map<String, Object> map = this.inspectorListCommon(list, percent);	
		//查询上次退回时填写的信息
		inspectorrecord inspRecord = inspectorRecordService.selectByPrimaryKey(inspectorRecordId);
		String sendbackReason = inspRecord.getNote();
		map.put("sendbackReason", sendbackReason);
		return map;
	}
	
	/**
	 * 巡检审核初审修改完成的任务
	 * 
	 * @param taskEffective
	 * @param day
	 * @param workerId
	 * @param firstDate
	 * @param lastDate
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/auditingForModifyCompleted", method = RequestMethod.POST)
	@ResponseBody
	public  Map<String, Object> auditingForModifyCompletedPost(HttpSession session, String sendbackUUID, int inspectorId, String workGroupCode) {
		int taskEffective = 4; //审核通过后taskEffective值
		Map<String, Object> map = new HashMap<>();
		//查询审核通过的的任务id和工作记录id
		List<Map<String,Integer>> idMapList = workerRecordService.getTaskIdsAndWorkerrecordIdsforModifyCompleted(sendbackUUID, workGroupCode,inspectorId);    //查询需要更新的任务id和记录id
		List<Integer> recordIds = new ArrayList<Integer>();
		List<Integer> taskIds = new ArrayList<Integer>();
		if(!idMapList.isEmpty()){  
			for (Map<String,Integer> map2 : idMapList) {
				recordIds.add(map2.get("recordId"));
				taskIds.add(map2.get("taskId"));
			}
		}else{
			map.clear();
			map.put(Constants.REPLAY, 0);
			map.put(Constants.MESSAGE, "审核失败!");
			return map;
		}	
		int userId = Integer.parseInt(session.getAttribute("userId").toString());
		int inspectorrecordId = 0;
		//获取计算工资节点  
		int salaryCountTiming = 0;
		List<VtdParameter> outsourcerCodeList = paramService.selectParamByType(Constants.OUTSOURCER_CODES);  //外包商组代码  数据库中只存一条信息  	
		VtdParameter param = outsourcerCodeList.get(0);
    	String[] outsourcerCodes = param.getParamValue().split(",");
    	boolean flag = true;
	    for (int i = 0; i < outsourcerCodes.length; i++) {
			if (workGroupCode.equals(outsourcerCodes[i])) {
				flag = false;  //审核的是外包工作者
			}
		}
		List<VtdParameter> paramList = null;
		if(flag){
			paramList = paramService.selectParamByType(Constants.SALARY_COUNT_TIMING);//查询结算设置用的参数 只有一条数据   自营
		}else{
			paramList = paramService.selectParamByType(Constants.OUTSOURCER_SALARY_COUNT_TIMING);//查询外包结算设置用的参数 只有一条数据  外包
		}
		if(!paramList.isEmpty()){
			VtdParameter vp = paramList.get(0);
			salaryCountTiming = Integer.parseInt(vp.getParamValue());
		}
		List<AlipayInfo> payList = null;
		inspector ins = inspectorService.getinspectorByUserId(userId);
		int insId = 0;
		if(ins != null){
			insId = ins.getInspectorId();
		}else{
			insId = 0;
		}
		//TODO 巡审审核初审修改插入工资单   
		int salaryCountFlag = 0;  //是否计算工资标识  0 未计算   1已计算
		if(taskEffective == 4 && salaryCountTiming == 2){    //当审核合格并且设置在初审计算工资是才向salary表插入数据
			payList = salaryService.insertSalaryForModifyCompleted(recordIds);
			salaryCountFlag = 1;
		}else if(taskEffective == 0 && salaryCountTiming == 1){
			salaryCountFlag = 0; 
		}else{
			salaryCountFlag = 9;  //9  不更新
		}
		//保存巡审审核有效时间 记录信息
		saveTheRecordOfInspectorMarkTimeForSecondInsp(recordIds, ins.getInspectorId(), userId, ins.getInspectorName(), true);
		taskService.updateAduitForInspectByDay(taskIds, taskEffective);  
		workerRecordService.updateAduitForModifyCompleted(taskEffective, insId, inspectorrecordId, salaryCountFlag, payList, recordIds);
		map.clear();
		map.put(Constants.REPLAY, 1);
		//支付宝支付是否成功
		StringBuffer sbf = new StringBuffer();
		if(payList!=null&&(!payList.isEmpty())){
			sbf.append("审核完成: ");
			for (AlipayInfo a : payList) {
				sbf.append("  |  "+a.getPayeeRealName());	
				if(a.getIsSuccess()){
					sbf.append("的任务已通过支付宝成功支付  查询代码:  "+a.getOutBizNo());	
				}else{
					sbf.append("支付宝支付失败, 可以在工资结算是一起结算      查询代码:  "+a.getOutBizNo()+"  |  ");	
				}
			}
			map.put(Constants.MESSAGE, sbf.toString());			
		}else{
			map.put(Constants.MESSAGE, "审核完成");			
		}
		return map;
	}
	
	/**
	 * 巡检审核初审修改的任务----不合格退回
	 * @param day                  退回时间  单位小时
	 * @param session          	   session
	 * @param note                 错误原因
	 * @param inspectedTaskIds     审核过的任务id 不一定是全部批次任务的id
	 * @param unqualifiedTaskIds   不合格的任务id
	 * @param workGroupCode        工作组代码
	 * @param inspectorId          初审审核员id
	 * @return
	 */
	@RequestMapping(value = "/sendBackForModifyCompleted", method = RequestMethod.POST)
	@ResponseBody
	public  Map<String, Object> sendBackForModifyCompletedPost(int day, HttpSession session, HttpServletRequest request,
			String note, String inspectedTaskIds, int[] unqualifiedTaskIds, String sendbackUUID, String workGroupCode, int inspectorId) {
		Map<String, Object> map = new HashMap<>();
		//查询审核通过的的任务id和工作记录id
		// taskList审核的任务id   unqualifiedTaskIds不合格的任务 id  taskIds 被退回的全部任务
		List<Map<String,Integer>> idMapList = workerRecordService.getTaskIdsAndWorkerrecordIdsforModifyCompleted(sendbackUUID, workGroupCode,inspectorId);    //查询需要更新的任务id和记录id
		List<Integer> recordIds = new ArrayList<Integer>();
		List<Integer> taskIds = new ArrayList<Integer>();
		if(!idMapList.isEmpty()){  
			for (Map<String,Integer> map2 : idMapList) {
				recordIds.add(map2.get("recordId"));
				taskIds.add(map2.get("taskId"));
			}
		}else{
			map.clear();
			map.put(Constants.REPLAY, 0);
			map.put(Constants.MESSAGE, "审核失败!");
			return map;
		}	
		//巡审退回批次UUID
		String inspectionSendbackUUID = UUID.randomUUID().toString().toUpperCase().replace("-", "");
		int userId = Integer.parseInt(session.getAttribute("userId").toString());
	    //审核记录信息
	    StringBuilder taskIdsSB = new StringBuilder();
	    for (int i = 0; i < unqualifiedTaskIds.length; i++) {
			if(i == 0){
				taskIdsSB.append(String.valueOf(unqualifiedTaskIds[i]));
			}else{
				taskIdsSB.append("_"+String.valueOf(unqualifiedTaskIds[i]));
			}
		}
	    
	    inspector ins = inspectorService.getinspectorByUserId(userId);
		int insId = 0;
		if(ins != null){
			insId = ins.getInspectorId();
		}else{
			insId = 0;
		}
		//保存巡审审核成功的有效时间
		saveTheRecordOfInspectorMarkTimeForSecondInsp(recordIds, ins.getInspectorId(), userId, ins.getInspectorName(), false);
		//保存审核记录
		InspectorRecordWithBLOBs record = new InspectorRecordWithBLOBs();
		record.setInspectorid(insId);
		record.setNote(note);
		record.setInspNum(recordIds.size());
		record.setInspectionSendbackUUID(inspectionSendbackUUID);
		record.setInspectedTaskIds(inspectedTaskIds);
		record.setUnqualifiedTaskIds(taskIdsSB.toString());
		inspectorRecordService.saveInspectorRecordWithBLOBs(record);
		int inspectorRecordId = inspectorRecordService.getMaxIdByInspectorId(userId);
		List<VtdParameter> outsourcerCodeList = paramService.selectParamByType(Constants.OUTSOURCER_CODES);  //外包商组代码  数据库中只存一条信息  	
		VtdParameter param = outsourcerCodeList.get(0);
    	String[] outsourcerCodes = param.getParamValue().split(",");
    	boolean outsourcerFlag = false;
	    for (int i = 0; i < outsourcerCodes.length; i++) {
			if (workGroupCode.equals(outsourcerCodes[i])) {
				outsourcerFlag = true;  //审核的是外包工作者
			}
		}
	    List<VtdParameter> sendbackCountList = paramService.selectParamByType(Constants.INSPECTION_SECOND_TO_FIRST_SENDBACK_COUNT); //巡审退回至初审次数  数据库中只存一条信息  	
	    VtdParameter param2 = sendbackCountList.get(0 );
	    int sendbackCount = Integer.parseInt(param2.getParamValue());
		if(outsourcerFlag){  //退回给外包商有次数限制超过次数就回收   
			// 不合格的时候添加不合格记录  当超过2次不合格的时候释放任务
			int releaseNum = workerRecordService.countReleaseTaskNum(recordIds, sendbackCount);
			boolean releaseFlag = false;
			if(releaseNum>0){
				this.saveSendbackTasksToServer(taskIds, inspectionSendbackUUID, request);
				releaseFlag= true;
			}
			//释放超过返回次数的任务 没超过的sendbackCount加1
			int num = workerRecordService.modifySendbackCountAndReleaseTask(recordIds,taskIds,releaseFlag,inspectionSendbackUUID,inspectorRecordId,userId);
			if(num==0){  // 如果unqualifiedCountNum为0 说明这次审核的所有任务都已经被释放  所以直接返回审核完成
				map.clear();
				map.put(Constants.REPLAY, 1);
				map.put(Constants.MESSAGE, "审核完成,不合格任务已被系统回收.");			
				return map;
			}
			//根据工作组代码将工作组内的下载锁定
			paramService.updateBackup1ByParamValueAndParamType(workGroupCode, Constants.WORK_GROUP, Constants.LOCK);
			day = 3600*1000*day;
		}else{
			day = 0;
		}
		if(note.length()==0){
			note = "未填写";
		}
		
		workerRecordService.updateInspectByDaySendbackWrokerRecords(recordIds,inspectorRecordId,inspectionSendbackUUID,day);
		map.clear();
		map.put(Constants.REPLAY, 1);
		map.put(Constants.MESSAGE, "不合格任务退回完成");
		return map;
	}
	
	/**
	 * 将初审修改超过退回次数的退回任务保存到服务器上
	 * @param taskIds
	 * @param sendbackUUID
	 * @param request
	 * @return
	 */
	public String saveSendbackTasksToServer(List<Integer> taskIds, String sendbackUUID, HttpServletRequest request) {
		String packName = sendbackUUID + ".zip";
		String url = request.getSession().getServletContext().getRealPath(Constants.SLASH);
        int psIndex = url.lastIndexOf("ps");
        url = url.substring(0, psIndex);
        url = url + "sendBackBackup";
		File f = new File(url);
		if (!f.exists()) {
			f.mkdir();
		}
		List<taskWithBLOBs> list = new ArrayList<>();
		for (Integer taskId : taskIds) {
			taskWithBLOBs taskWithBLOBs = new taskWithBLOBs();
			taskWithBLOBs = taskService.selectByPrimaryKey(taskId); // 将wav文件去掉    
			list.add(taskWithBLOBs);
		}
		File zipFile = new File(url + Constants.SLASH + packName);
		if (zipFile.exists()) {
			zipFile.delete();
		}
		try {
			zipFile.createNewFile();
			FileOutputStream fos = new FileOutputStream(zipFile);
			ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos));
			inspectWriteInZIP(list, zos, Constants.WAV,null);
//			inspectWriteInZIP(list, zos, Constants.TAG, null);
			inspectWriteInZIP(list, zos, Constants.TEXTGRID, null);
			zos.close();// 不关闭,最后一个文件写入为0kb
			fos.flush();
			fos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return packName;
	}
	
	/**
	 * 审核员页面 查询 超过修改次数  被系统回收列表
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/queryRecycledBySystemList", method = RequestMethod.POST)
	public Map<String, Object> queryRecycledBySystemListPost(HttpSession session, int page) {
		Map<String, Object> map = new HashMap<>();
		int userId = Integer.parseInt(session.getAttribute("userId").toString());
		inspector ins = inspectorService.getinspectorByUserId(userId);
		//查询数据
	    List<Map<String,Object>> list = workerRecordService.queryRecycledBySystemListByInspectorId(ins.getInspectorId(), page, Constants.ROW);	
		DateFormat df = new SimpleDateFormat(Constants.DATETIME_FORMAT);
		for (Map<String, Object> map2 : list) {
			Date sendbackDate = (Date)map2.get("sendbackTime");
			String sendbackDateString = df.format(sendbackDate);
			map2.put("sendbackDateTime", sendbackDateString);
			String downloadPackName = map2.get("sendbackUUID")+".zip";
			map2.put("downloadPackName", downloadPackName);
		}
		int totle = workerRecordService.queryRecycledBySystemListByInspectorIdCount(ins.getInspectorId());
		int totlePage = (int) Math.ceil((double) totle / (double) Constants.ROW);
		
		if(list.isEmpty()){
			map.put(Constants.LIST, "");
		}else{
			map.put(Constants.LIST, list);
		}
		map.put(Constants.TOTLE, totle);
		map.put(Constants.TOTLE_PAGE, totlePage);  
		return map;
	}
	
	/**
	 * 审核员页面 查询 超时 被系统回收列表
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/queryModifyTimeOutList", method = RequestMethod.POST)
	public Map<String, Object> queryModifyTimeOutListPost(HttpSession session, int page) {
		Map<String, Object> map = new HashMap<>();
		int userId = Integer.parseInt(session.getAttribute("userId").toString());
		inspector ins = inspectorService.getinspectorByUserId(userId);
		//查询数据
	    List<Map<String,Object>> list = workerRecordService.queryModifyTimeOutListByInspectorId(ins.getInspectorId(), page, Constants.ROW);	
	    DateFormat df = new SimpleDateFormat(Constants.DATETIME_FORMAT);
		for (Map<String, Object> map2 : list) {
			Date sendbackDate = (Date)map2.get("sendbackTime");
			String sendbackDateString = df.format(sendbackDate);
			map2.put("sendbackDateTime", sendbackDateString);
			long timeLimit = Long.parseLong(map2.get("timeLimit").toString());
			double sendbackLimitHour = Math.round(((timeLimit/1000d/3600d)*100d))/100d;
			map2.put("sendbackLimitHour", sendbackLimitHour);
		}
		//分页
		int totle = workerRecordService.queryModifyTimeOutListByInspectorIdCount(ins.getInspectorId());
		int totlePage = (int) Math.ceil((double) totle / (double) Constants.ROW);
		if(list.isEmpty()){
			map.put(Constants.LIST, "");
		}else{
			map.put(Constants.LIST, list);
		}
		map.put(Constants.TOTLE, totle);
		map.put(Constants.TOTLE_PAGE, totlePage);  
		return map;
	}
	
	private Object getNotice(HttpSession session) {
		String noticeFlag = session.getAttribute(Constants.NOTICE_FLAG).toString(); //通知公告标志
		if(noticeFlag.equals("1")){
			//查询出更新时间最靠前的一条公告显示
			VtdNotice notice = noticeService.getOneNoticeOrderByUpdateTimeDesc();
			return notice;
		}else{
			return "";
		}
	}
	
	/**
	 * 初审结算时更新finalMd5字段 
	 * @param workerId
	 * @param taskEffective
	 * @param uploadUUID
	 * @return
	 */
	private int auditingUpdateFinalMd5(int workerId, String uploadUUID){
//		long start = System.currentTimeMillis();
		//查询任务记录id 任务id 任务文件textgrid
		List<Map<String, Object>> results = workerRecordService.getTaskIdsRecordIdsAndFilesForAuditingUpdateFinalMd5(workerId, uploadUUID);
		int count = 0;
		for (Map<String, Object> m : results) {
//			System.out.println(DigestUtils.md5Hex((byte[])(m.get("bytes"))));
			int recordId = Integer.parseInt(m.get("recordId").toString());
			String md5 = DigestUtils.md5Hex((byte[])(m.get("bytes")));
			//更新finalMd5字段
			int num = workerRecordService.updateFinalMd5ByRecordId(recordId, md5);
			count = count + num;
		}
//		long end = System.currentTimeMillis();
//		System.out.println("保存finalMd5用时: "+(end-start)+"毫秒");
		return count;
	}
	
	/**
	 * 巡审结算时更新finalMd5字段 
	 * @param workerId
	 * @param taskEffective
	 * @param uploadUUID
	 * @return
	 */
	private int inspectByDayUpdateFinalMd5(List<Integer> recordIds){
//		long start = System.currentTimeMillis();
		//查询任务记录id 任务id 任务文件textgrid
		List<Map<String, Object>> results = workerRecordService.getTaskIdsRecordIdsAndFilesForInspectByDayUpdateFinalMd5(recordIds);
		int count = 0;
		for (Map<String, Object> m : results) {
//			System.out.println(DigestUtils.md5Hex((byte[])(m.get("bytes"))));
			int recordId = Integer.parseInt(m.get("recordId").toString());
			String md5 = DigestUtils.md5Hex((byte[])(m.get("bytes")));
			//更新finalMd5字段
			int num = workerRecordService.updateFinalMd5ByRecordId(recordId, md5);
			count = count + num;
		}
//		long end = System.currentTimeMillis();
//		System.out.println("保存finalMd5用时: "+(end-start)+"毫秒");
		return count;
	}
	
	/**
	 * 包审结算时更新finalMd5字段 
	 * @param workerId
	 * @param taskEffective
	 * @param uploadUUID
	 * @return
	 */
	private int inspectByPackageUpdateFinalMd5(int workerId, int packId){
//		long start = System.currentTimeMillis();
		//查询任务记录id 任务id 任务文件textgrid
		List<Map<String, Object>> results = workerRecordService.getTaskIdsRecordIdsAndFilesForInspectByPackageUpdateFinalMd5(workerId, packId);
		int count = 0;
		for (Map<String, Object> m : results) {
//			System.out.println(DigestUtils.md5Hex((byte[])(m.get("bytes"))));
			int recordId = Integer.parseInt(m.get("recordId").toString());
			String md5 = DigestUtils.md5Hex((byte[])(m.get("bytes")));
			//更新finalMd5字段
			int num = workerRecordService.updateFinalMd5ByRecordId(recordId, md5);
			count = count + num;
		}
//		long end = System.currentTimeMillis();
//		System.out.println("保存finalMd5用时: "+(end-start)+"毫秒");
		return count;
	}
	
	/**
	 * 快速审核结算时更新finalMd5字段 
	 * @param workerId
	 * @param taskEffective
	 * @param uploadUUID
	 * @return
	 */
	private int quickInspectionPosteUpdateFinalMd5(int workerId, int packId){
//		long start = System.currentTimeMillis();
		//查询任务记录id 任务id 任务文件textgrid
		List<Map<String, Object>> results = workerRecordService.getTaskIdsRecordIdsAndFilesForQuickInspectionPosteUpdateFinalMd5(workerId, packId);
		int count = 0;
		for (Map<String, Object> m : results) {
//			System.out.println(DigestUtils.md5Hex((byte[])(m.get("bytes"))));
			int recordId = Integer.parseInt(m.get("recordId").toString());
			String md5 = DigestUtils.md5Hex((byte[])(m.get("bytes")));
			//更新finalMd5字段
			int num = workerRecordService.updateFinalMd5ByRecordId(recordId, md5);
			count = count + num;
		}
//		long end = System.currentTimeMillis();
//		System.out.println("保存finalMd5用时: "+(end-start)+"毫秒");
		return count;
	}
	
	/**
	 * 保存初审审核有效时间 记录信息
	 * @param inspectorId 审核员id
	 * @param userId  用户名
	 * @param inspectorName 审核员姓名
	 * @param workerId 工作者id
	 * @param uploadUUID 上传批次id 
	 * @param sendBackType 退回类型
	 * @param unqualifiedTaskIds 不合格任务id
	 * @param taskEffective 3为审核通过 0位不通过
	 * @return
	 */
	private int saveTheRecordOfInspectorMarkTimeForFirstInsp(int inspectorId, int userId, 
			String inspectorName, int workerId, String uploadUUID, 
			int sendBackType, int[] unqualifiedTaskIds, int taskEffective){
		//查询审核的标注时间
		double inspMarkTime = imtrService.queryFirstInspectorMarkTime(workerId,uploadUUID,sendBackType,unqualifiedTaskIds, taskEffective);
		//添加审核标注时间记录
		InspectorMarkTimeRecord imtr = new InspectorMarkTimeRecord();
		imtr.setId(UUID.randomUUID().toString().replace("-", "").toUpperCase());
		imtr.setInspectorId(inspectorId);
		imtr.setUserId(userId);
		imtr.setInspectorName(inspectorName);
		if(taskEffective==3){
			imtr.setQualified(true);
			imtr.setQualifiedMarkTime(inspMarkTime);
		}else{
			imtr.setQualified(false);
			imtr.setUnqualifiedMarkTime(inspMarkTime);
		}
		int count = imtrService.saveOne(imtr);
		return count;
	}
	
	/**
	 * 保存巡审审核有效时间 记录信息
	 * @param recordIds  任务记录id
	 * @param inspectorId 审核员id
	 * @param userId 工作者id
	 * @param inspectorName 审核员姓名
	 * @param isQualified 是否合格
	 * @return
	 */
	private int saveTheRecordOfInspectorMarkTimeForSecondInsp(List<Integer> recordIds, int inspectorId, 
			int userId, String inspectorName, boolean isQualified){
		//查询审核的标注时间
		double inspMarkTime = imtrService.querySecondInspectorMarkTime(recordIds);
		//添加审核标注时间记录
		InspectorMarkTimeRecord imtr = new InspectorMarkTimeRecord();
		imtr.setId(UUID.randomUUID().toString().replace("-", "").toUpperCase());
		imtr.setInspectorId(inspectorId);
		imtr.setUserId(userId);
		imtr.setInspectorName(inspectorName);
		if(isQualified){
			imtr.setQualified(true);
			imtr.setQualifiedMarkTime(inspMarkTime);
		}else{
			imtr.setQualified(false);
			imtr.setUnqualifiedMarkTime(inspMarkTime);
		}
		int count = imtrService.saveOne(imtr);
		return count;
	}
	
	/**
	 * 保存巡审 快速审核有效时间 记录信息
	 * @param packId
	 * @param workerIds
	 * @param taskEffective
	 * @param inspectorId
	 * @param userId
	 * @param inspectorName
	 * @return
	 */
	private int saveTheRecordOfInspectorMarkTimeForQuickInsp(int packId, int[] workerIds, int taskEffective, 
			int inspectorId, int userId, String inspectorName){
		//查询审核的标注时间
		double inspMarkTime = imtrService.queryQuickInspectorMarkTime(packId, workerIds, taskEffective);
		//添加审核标注时间记录
		InspectorMarkTimeRecord imtr = new InspectorMarkTimeRecord();
		imtr.setId(UUID.randomUUID().toString().replace("-", "").toUpperCase());
		imtr.setInspectorId(inspectorId);
		imtr.setUserId(userId);
		imtr.setInspectorName(inspectorName);
		if(taskEffective==1){
			imtr.setQualified(true);
			imtr.setQualifiedMarkTime(inspMarkTime);
		}else{
			imtr.setQualified(false);
			imtr.setUnqualifiedMarkTime(inspMarkTime);
		}
		int count = imtrService.saveOne(imtr);
		return count;
	}
	
	
	/**
	 * 初审审核修改有效时间为0的任务的有效时间为0.001
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/updateWorkerRecordChangeZeroTo0001", method = RequestMethod.POST)
	public Map<String, Object>  updateWorkerRecordChangeZeroTo0001(int workerId, String uploadUUID, HttpSession session) {
		Map<String, Object> map = new HashMap<>();
		boolean isSuccess = workerRecordService.updateWorkerRecordChangeZeroTo0001(workerId, uploadUUID);
		if(isSuccess){
			map.put(Constants.REPLAY, 1);
			map.put(Constants.MESSAGE, "修改成功!");
			return map;
		}else{
			map.put(Constants.REPLAY, 0);
			map.put(Constants.MESSAGE, "修改失败!");
			return map;
		}		
	}
}
